How does the C process a conditional statement such as n >= 1 <= 10
?
I initially thought that it would get evaluated as n >= 1 && 1 <= 10
, as it would be evaluated in Python. Since 1 <= 10
is always true, the second porition of the and
is redundant (the boolean value of X && True
is equivalent to the boolean value of X
).
However, when I run it with n=0
, the conditional gets evaluated to true. In fact, the conditional always seems to evaluate to true.
This was the example I was looking at:
if (n >= 1 <= 10)
printf("n is between 1 and 10\n");
>=
operator is evaluated from left to right, so it is equal to:
if( ( n >= 1 ) <= 10)
printf("n is between 1 and 10\n");
The first ( n >= 1 )
is evaluated either as true or false, which is equal to either 1 or 0. Then that result of 1 or 0 is compared to result <= 10
which will always evaluate to true.
Thus the statement printf("n is between 1 and 10\n");
will always be printed