【发布时间】:2016-12-31 18:07:36
【问题描述】:
我无法理解这个程序的输出:
#include<iostream>
using namespace std;
int main()
{
int x = 1 , y = 1, z = 1;
cout << ( ++x || ++y && ++z ) << endl; //outputs 1;
cout << x << " " << y << " " << z ; //x = 2 , y = 1 , z = 1;
return 0;
}
输出:
1
2 1 1
如果首先评估||,那么这个输出很好,但是this 文章说&& 的优先级高于||,因此必须先评估它。如果是这种情况,那么根据我的输出应该是:
1
1 2 2
因为++y && ++z 将评估为true,因此不会评估++x。
【问题讨论】:
-
Precedence != 评估顺序。
-
那我如何确定评估顺序呢?感谢您的意见。
-
我明白了@molbdnilo,谢谢
-
Eric Lippert 有一篇很棒的文章解释了difference between precedence, associativity, and order of evaluation。它更多地关注 C#,但也处理 C++。只有一件事:他说在 C++ 中评估顺序是免费的(与 C# 不同,它严格从左到右)。好吧,也有例外:布尔运算符 AND 和 OR 要求从左到右,因此可以应用短路,如本例所示。
标签: c++ operators operator-precedence logical-or logical-and