Why is a condition like (0 < a < 5) always true?

Unlike Python (which has operator chaining), C evaluates the condition as:

(0 < a) < 5

The result of (0 < a) is either 0 or 1, both of which are less than 5, so the overall condition is true.

In C, a range test must be written:

0 < a && a < 5

Note that the Python script:

for a in range(-1,7):
  if 0 < a < 5:
    print a, " in range"
  else:
    print a, " out of range"

produces the output:

-1  out of range
0  out of range
1  in range
2  in range
3  in range
4  in range
5  out of range
6  out of range

The ‘equivalent’ C program using the same if condition would, of course, produce the answer ‘in range’ for each value.

Leave a Comment