-1

I tried this code on ideone and on Visual Studio 2013:

int main()
{
    int x = 5;
    if(4 < x < 6)
    {
        return 1;
    }
    return 0;
}

It produces a runtime error on ideone but works perfectly fine on VS.

What does the standard say about this nonconsistent behaviour. I know there are compilation warnings but I'm wondering why this isn't natively/officially supported?

Gizmo
  • 1,990
  • 1
  • 24
  • 50

2 Answers2

12

This is valid code in both C and C++, but does not do what you meant. It is the same as:

bool temp = (4 < x);
if (temp < 6) // always true
     return 1;  // this is EXIT_FAILURE
// dead code here returning EXIT_SUCCESS

The result of relational operators on primitive types is bool (in C++, int in C), and bool gets promoted to int for the subsequent comparison, giving the value 0 or 1, always.

Since both 0 and 1 are less than 6, the condition is always true.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Is it guaranteed to do it in that order? It would make sense if it does, but could an optimizing compiler decide to do `bool temp = (x < 6); if(4 < temp)` instead? – wolfPack88 Jan 07 '15 at 15:37
  • 4
    @wolfPack88: The order is guaranteed by the associativity rules. If you had `f() < x < g()` you wouldn't know whether `f()` or `g()` got called first, but `x` would be compared to the result of `f()` first. – Ben Voigt Jan 07 '15 at 15:38
  • 1
    probably should add that if( 4 < x and x < 6 ) does what he wants – Slava Jan 07 '15 at 15:41
  • good to know that :) Can accept in 5 min, and wow, this answer literally exploded in ups – Gizmo Jan 07 '15 at 15:42
  • 4
    No, not literally. Figuratively. The opposite of literally. – Benjamin Lindley Jan 07 '15 at 15:43
5

Ben Voigt's answer is correct, of course, but I want to address the "runtime error" part of the question:

It's works just as fine in Visual Studio as it does on ideone. The return 1; is reported by ideone as a runtime error. Visual Studio has the same return value; it just doesn't complain as loudly as ideone does.

Cornstalks
  • 37,137
  • 18
  • 79
  • 144
  • 1
    Indeed, because `EXIT_SUCCESS` in `stdlib.h` is defined as `0`, and this code takes the other branch. – Ben Voigt Jan 07 '15 at 15:41