Quick Q: Is (4 > y > 1) a valid statement in C++? How do you evaluate it if so?

Quick A: This is not a valid statement.

Recently on SO:

Is (4 > y > 1) a valid statement in C++? How do you evaluate it if so?

The statement (4 > y > 1) is parsed as this:

((4 > y) > 1)

The comparison operators < and > evaluate left-to-right.

The 4 > y returns either 0 or 1 depending on if it's true or not.

Then the result is compared to 1.

In this case, since 0 or 1 is never more than 1, the whole statement will always return false.

Add a Comment

Comments are closed.

Comments (2)

1 0

R. A. Berliner said on Jan 25, 2018 05:01 AM:

The "Quick A" contradicts the explanation. It's a valid expression, as in: it is well-formed C++ and has defined behavior. It just doesn't have the same (or any useful) meaning as in mathematics.
0 0

justbart said on Jan 31, 2018 07:16 PM:

Not always, Adrien. operator < doesn't have to return a bool. wink


#include <iostream>

class Y {
};

int operator >(int, Y) {
return 2;
}

int main () {
std::cout << std::boolalpha;
Y y;
std::cout << (4 > y > 1); // prints 'true'
}