是(4> y> 1)是C ++中的有效语句吗?如果是这样,你如何评价? [英] Is (4 > y > 1) a valid statement in C++? How do you evaluate it if so?
问题描述
这是一个有效的表达式吗?如果是这样,你可以重写它,使它更有意义吗?例如,是否与(4> y&& y> 1)
相同? c>(4> y> 1)语句
被解析为:
((4> y)> 1)
比较运算符<
和>
评估从左到右。
4> y
根据是否为真返回 0
或 1
。 >
然后结果与1比较。
在这种情况下,由于 0
或 1
永远不会超过 1
,整个语句总是返回false 。
有一个例外:
如果 y
是一个类,并且>
。
例如,这将无法编译:
class mytype {
};
mytype operator>(int x,const mytype& y){
return mytype();
}
int main(){
mytype y;
cout<< (4> y> 1)< endl;
return 0;
}
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?
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;
}
这篇关于是(4> y> 1)是C ++中的有效语句吗?如果是这样,你如何评价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!