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.


There is one exception though:

If y is a class and the > operator has been overloaded to do something unusual. Then anything goes.

For example, this will fail to compile:

class mytype{
};

mytype operator>(int x,const mytype &y){
    return mytype();
}

int main(){

    mytype y;

    cout << (4 > y > 1) << endl;

    return 0;
}

Leave a Comment