Why can't we do three-way comparison in C++?

The expression

2 < x < 9

is grouped as

(2 < x) < 9

And since 2 < x is either false (0) or true (1), and both are less than 9, it's always true.

So unless you use overloaded operators for a non-built-in type x (then a 3-way comparison would be possible if 2 < x were to return an instance of a proxy object on which < is defined), if you want to test if x is in the interval (2, 9) you need to write it the way you have.


Just because this language doesn't have that feature.

It could have been made to, but this would contrast with C in a non-compatible way.

C could have been made to, but the designers simply didn't do that.

You already have the correct way to do it.

Some different (and newer!) languages do support this.


the comparison operators in c++ takes as an argument two values. when you are writing a<b it is the same as operator<(a,b). and the return value of operator< is bool. when you are calling a function in c++, it is computing the expression of its arguments and then passing it to that function, so calling a<b<c is same as operator<(operator<(a,b),c)

basically, the answer to your question is that in c++ there is no comparison operator (less than, greater than...) that takes three arguments

Tags:

C++