Search code examples
c++expression-evaluation

If statement without '&&' works?


int n = 5;    
if(2<=n<=20) 
 {
  cout << "hello";
 }

In the above code, it does not give an error, it runs successfully and gives "hello" as output.

But we have to use && in this kind of equation.
Can anyone explain this?


Solution

  • <= is left-associative in C++, so the expresion is parsed as ((2 <= n) <= 20). 2 <= n is of type bool, which can implicitly convert to int: true converts to 1 and false converts to 0.

    Both of these are <= 20, so the condition is effectively always true.


    Note that the above assumes n is an int or another primitive numerical type. If n is a user-defined class with operator <= overloaded, the associativity bit is still true, but the part about implicit conversions may or may not apply, based on the return type and semantics of that overloaded operator.