这是一个有效的表达吗?如果是这样,您能否重写它以使其更有意义?例如,它是否与 (4 > y && y > 1) 相同?您如何评估链式逻辑运算符?
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?
语句 (4 > y > 1) 解析如下:
((4 > y) > 1)
比较运算符 < 和 > 从左到右评估.
The comparison operators < and > evaluate left-to-right.
4 >y 返回 0 或 1 取决于它是否为真.
The 4 > y returns either 0 or 1 depending on if it's true or not.
然后将结果与 1 进行比较.
Then the result is compared to 1.
在这种情况下,由于0或1永远不会超过1,整个语句将始终返回false强>.
In this case, since 0 or 1 is never more than 1, the whole statement will always return false.
不过有一个例外:
如果 y 是一个类并且 > 运算符已被重载以执行不寻常的操作.然后一切顺利.
If y is a class and the > operator has been overloaded to do something unusual. Then anything goes.
例如,这将无法编译:
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++ 中的有效语句吗?如果有,你如何评价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
编译器如何处理编译时分支?What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
在 C/C++ 中检查空指针Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
比较运算符的数学式链接-如“if((5<j<=1))&quMath-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
“if constexpr()"之间的区别与“if()"Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++,'if' 表达式中的变量声明C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)