Can*_*aIT 1 c++ compiler-construction visual-studio
我只测试了两个简单的表达式,尽管相反的值会产生相同的结果.
int main() {
unsigned int a = 50, b = 33, c = 24, d = 12;
if (a != b < c){
/*a is not equal to b, so the bool is converted to 1 and 1 is less than c*/
cout << "This is apparent" << endl;
}
if (a != b > c){
/* a is not equal to b, so the bool is converted to one and 1 is not more than c.
* The expression still evaluates to true.
* Why is this? Is the compiler messing with something? */
cout << "This is apparent" << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Kei*_*son 11
唯一"有趣的业务"是编译器完全正在做它应该做的事情.
<,>和其他关系运算符绑定比=和更紧密!=,所以这:
if (a != b < c)
Run Code Online (Sandbox Code Playgroud)
相当于:
if (a != (b < c))
Run Code Online (Sandbox Code Playgroud)
由于a既不是也不0是1,它将不等于任何相等或关系运算符的结果.
为了比较的结果!=来c,你可以这样写:
if ((a != b) < c)
Run Code Online (Sandbox Code Playgroud)
当您不确定您正在使用的运算符的相对优先级,或者您的读者可能不确定时,您应该使用括号.我非常了解C,但我必须检查标准以确保关系运算符和相等运算符的相对优先级.
但在这种特殊情况下,我想不出任何理由去做你正在做的事情(除了作为理解表达评价的练习,如果这就是你正在做的事情,那是完全合理的).如果我if ((a != b) < c)在实际代码中看到,我可能会要求作者重写它.
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |