什么是"序列点"?
未定义的行为和序列点之间的关系是什么?
我经常使用有趣和复杂的表达方式a[++i] = i;,让自己感觉更好.我为什么要停止使用它们?
如果您已阅读此内容,请务必访问后续问题重新加载未定义的行为和序列点.
(注意:这是Stack Overflow的C++常见问题解答的一个条目.如果你想批评在这种形式下提供常见问题解答的想法,那么发布所有这些的元数据的发布将是这样做的地方.这个问题在C++聊天室中受到监控,其中FAQ的想法一开始就出现了,所以你的答案很可能被那些提出想法的人阅读.)
在回答了这个问题之后,对于有问题的代码是否是未定义的行为进行了长时间的讨论.这是代码:
std::map<string, size_t> word_count;
word_count["a"] = word_count.count("a") == 0 ? 1 : 2;
Run Code Online (Sandbox Code Playgroud)
首先,至少没有具体说明这一点已经确定.结果根据首先评估分配的哪一侧而不同.在我的回答中,我跟踪了四个结果案例中的每一个,其中包括首先评估哪一方的因素以及该元素之前是否存在.
还有一个简短的表格:
(x = 0) = (x == 0) ? 1 : 2; //started as
(x = 0) = (y == "a") ? 1 : 2; //changed to
Run Code Online (Sandbox Code Playgroud)
我声称它更像是这样的:
(x = 0, x) = (x == 0) ? 1 : 2; //comma sequences x, like [] should
Run Code Online (Sandbox Code Playgroud)
最后,我找到了一个似乎对我有用的例子:
i = (++i,i++,i); //well-defined per SO:Undefined Behaviour and Sequence Points
Run Code Online (Sandbox Code Playgroud)
回到原文,我把它分解成相关的函数调用,以便更容易理解:
operator=(word_count.operator[]("a"), word_count.count("a") == 0 …Run Code Online (Sandbox Code Playgroud) c++ operator-precedence undefined-behavior sequence-points unspecified-behavior