Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. 53) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined. [Example:
i = v[i++]; // the behavior is unspecified i = 7, i++, i++; // i becomes 9 i = ++i + 1; // the behavior is unspecified i = i + 1; // the value of i is incremented
—end example]
我很惊讶地发现,i = ++i + 1
这个表达式会使得i
的值变成未定义。
有没有人知道是否有某种编译器实现不会针对以下情况返回2
?
int i = 0;
i = ++i + 1;
std::cout << i << std::endl;
事实上,operator=
有两个参数,第一个始终是i
的引用。在这种情况下,评估顺序并不重要。我没有看到任何问题,除了C++标准的禁忌.
请不要考虑那些参数顺序对评估很重要的情况。例如,++i + i
显然是未定义的。请只考虑我的情况i = ++i + 1
。
为什么C++标准禁止这样的表达式?
operator=
不是整数类型的序列点。 - Andreas Brincki= ++i +1
是未指定行为?”)不准确。 - mlvljr