mb8*_*b84 3 c++ operator-precedence undefined-behavior sequence-points c++03
对于C++ 03,标准说,在&&运算符的左右操作数之间有一个序列点,因此左操作符的所有副作用都发生在访问右操作符之前.
所以
int i = 0;
if (++i && i--)
std::cout << i;
Run Code Online (Sandbox Code Playgroud)
定义明确,保证输出0.
但是这个问题是什么:只有左操作数不是,才评估右操作数0?它似乎是一个细节,但对我来说,标准只保证操作数之间的序列点,而不是右操作数永远不会依赖于左操作数进行评估/访问.
例如
int arr[10];
int pos; // somehow set to a value from 0 to 10
while (pos < 10 && arr[pos] != 0)
pos++;
Run Code Online (Sandbox Code Playgroud)
这个定义得很好吗?pos可能是从开始10或到达10.左操作数没有副作用,与右操作数一致.我arr[10] != 0有从未履行的保证吗?
编辑:
感谢评论和回答,现在很清楚:
5.14p2: "The result is a bool. If the second expression is evaluated,
every value computation and side effect associated with the first expression
is sequenced before every value computation and side effect associated with
the second expression."
Run Code Online (Sandbox Code Playgroud)
是序列点的含义.
5.14p1: "Unlike &, && guarantees left-to-right evaluation: the second operand is
not evaluated if the first operand is false."
Run Code Online (Sandbox Code Playgroud)
是短路的意思.
没有第二个的第一个将使我的例子未定义.谢谢.