I wrote this in cpp but i am getting 2 why? please help?

#include
2. main_program {
3. const int a = 2;
4. if (0 < a < 1.5)
5. cout << a;
6. else
7. cout << 2*a;
8. }

The part:

doesn’t do what you think it does: < has left associativity, so the expression 0 < a < 1.5 is parsed as:

(0 < a) < 1.5

0 < a is a bool expression, equal to true:

(true) < 1.5

The other operand of the <, 1.5, is a double, so true is promoted to that, taking the value 1.0:

(1.0) < 1.5

This expression then evaluates to true, so the “then” branch of the if fires, and line 5 (not 7) is executed.

3 Likes