Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

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

Is that a valid expression? If so, can you rewrite it so that it makes more sense? For example, is it the same as (4 > y && y > 1)? How do you evaluate chained logical operators?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...