int a = 2;
while (1 < a < 5) {
printf("%d\n", a);
a = a + 1;
}
In a C program, I have used the above code, but it is always counting infinitely. That means the test condition of the while loop is always true. But I could not understand why this is happening.
1 < a < 5
is grouped as (1 < a) < 5
.
For your value of a
, 1 < a
returns 1
(true), so now your expression becomes 1 < 5
, which always evaluates to 1
, that's why you end up with an infinite loop.
The behavior you want can be obtained by writing while((1 < a) && (a < 5))
instead.