how does c evaluate less than and more than expretion?

187 Views Asked by At

I would like to know how i is evaluated in this code in C language ?

    int x = 10, y = 20, z = 5, i;
    i = x < y < z;
    printf("%d\n",i);
1

There are 1 best solutions below

0
On BEST ANSWER

The result of a relational operator is either integer 1 if the condition is true or 0 otherwise. And relational operators evaluates from left to right.

So this statement

i = x < y < z;

is equivalent to

i = ( x < y ) < z;

and as x is less than y then it can be also rewritten like

i = 1 < z;

that initialize the variable i by 1 because 1 is less than 5.

From the C Standard (6.5.8 Relational operators)

6 Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.107) The result has type int.

If you will rewrite the statement like

i = x < y && y < z;

then the result of the expression will be equal to 0 because y is not less than z.