1

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);
mch
  • 9,424
  • 2
  • 28
  • 42
Sofia Lazrak
  • 264
  • 5
  • 18
  • 5
    `-5<-2` is true, i.e. equal to 1. and `1 < -1` is false. – Damien Nov 25 '21 at 16:32
  • 4
    Why do you think it should be true? I assume because you expected `-5<-2<-1` to mean `(-5 < -2) && (-2 < -1)`. It does not. There are other languages where it does work that way, most notably Python (and it also will evaluate `-2` only once). But in C, `-5<-2<-1`, means `(-5 < -2) < -1`. – Karl Knechtel Nov 25 '21 at 16:32
  • 3
    I think you are looking for `(-5 < -2) && (-2 < -1)` – Hollyol Nov 25 '21 at 16:33
  • Thanks everyone. Very clear now – Sofia Lazrak Nov 25 '21 at 16:37

1 Answers1

2

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335