-1

I would like to check if value B is between A and C , my first try is if(A < B < C) , however the result is not right ,after I try if(A < B && B < C) and it works well

The second method is intuitive to me , but I do not know why first one fails and what C++ actually does in if(A < B < C) operation? Can someone explains to me , Thanks!

Pro_gram_mer
  • 749
  • 3
  • 7
  • 20
  • 2
    You can't chain relational operators. What really happens is `A < B` will evaluate to `1` or `0` and that'll be compared with `C`. – mediocrevegetable1 Sep 02 '21 at 04:20
  • A good [book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) should be preferred to random coding. – Evg Sep 02 '21 at 06:48
  • In Python (where I guess you've seen this) a "logical chain" like `a < b < c` is shorthand for `a < b and b < c`. Very few languages work like Python in that regard. (Note that in Python, you can also write weird things like `3 > 2 < 5 in [2,3,4]`.) – molbdnilo Sep 02 '21 at 09:25

2 Answers2

2

In C++, the < operator has left-to-right associativity. That means your expression A < B < C can be written (more verbosely) as (A < B) < C. First, A < B is evaluated, say res. Then, that intermediate result is used to evaluate res < C which is ultimately used by the if statement.

And, as you can see that it is very much different from the expression A < B && B < C.

0

A < B evaluates to a boolean value, so then you're comparing C to a boolean.

true < C doesn't make sense, no? Unless C itself is a boolean, in which case, why are you using less/greater than haha.

fortytoo
  • 452
  • 2
  • 11