Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading