Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is if (2 < 9 < 3) true?

Tags:

c

This was a question in my preparation exam:

int val = 0;
int x = 0;
int y = 1;
if (x < val < y)
    printf(" true ");
else
    printf(" false ");

Why is this true? I tried changing x and val and it ignored those changes, as long as y was larger than 0 (so 1, 2, 3...) the statement was true. So for example: if (3 < 9 < 2) will be true.

like image 743
Saroth Nevertale Avatar asked Jan 17 '21 20:01

Saroth Nevertale


2 Answers

( 2 < 9 < 3 ) is evaluated as ( ( 2 < 9 ) < 3).
In the first step 2 < 9 is evaluated to be true, which is represented as integer value 1 and results in ((1) < 3) for the second step.
That is obviously true.

You probably wanted something like ((x < val) && ( val < y)).

like image 188
Yunnosch Avatar answered Oct 12 '22 12:10

Yunnosch


The first is check whether x < value. If true, it return 1 so the next is check whether 1 < y.

like image 20
Itati Avatar answered Oct 12 '22 11:10

Itati