Why is this inequality False in C?

Anyone can enlighten me on why -5<-2<-1 returns 0 in C when I would expect it to return 1(True)?

printf("%d", -5<-2<-1);

>Solution :

This expression

-5<-2<-1

is equivalent to

( -5<-2 ) < -1

because the operator < evaluates left to right.

As -5 is less than -2 then the value of the sub-exoression

( -5 < -2 )

is integer value 1. So you have

1 < -1

and the result of this expression is 0 that is logical false.

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. The result has type
int
.

It seems you mean - 5 < -2 && -2 < -1

Leave a Reply