操作数的求值顺序
在表达式 a + b
中,是否保证 a
在 b
之前计算,还是未指定计算顺序?我认为是后者,但我很难在标准中找到明确的答案。
因为我不知道 C 处理这个问题是否与 C++ 不同,或者评估顺序规则是否在 C++11 中得到简化,所以我将把这个问题标记为所有三个。
In the expression a + b
, is a
guaranteed to be evaluated before b
, or is the order of evaluation unspecified? I think it is the latter, but I struggle to find a definite answer in the standard.
Since I don't know whether C handles this different from C++, or if evaluation order rules were simplified in C++11, I'm gonna tag the question as all three.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在C++中,对于用户定义类型
a + b
是一个函数调用,标准是这样说的:对于普通操作员,标准规定:
对于 C++11,这些没有改变。然而,第二个中的措辞发生了变化,表示顺序是“未排序”而不是未指定,但本质上是相同的。
我没有 C 标准的副本,但我想那里也是一样的。
In C++, for user-defined types
a + b
is a function call, and the standard says:For normal operators, the standard says:
These haven't been changed for C++11. However, the wording changes in the second one to say that the order is "unsequenced" rather than unspecified, but it is essentially the same.
I don't have a copy of the C standard, but I imagine that it is the same there as well.
它是未指定。
参考 - C++03 标准:
第 5 节:表达式,第 4 段:
It is Unspecified.
Reference - C++03 Standard:
Section 5: Expressions, Para 4:
C++0x FDIS 第 1.9 节“程序执行”§15 与 C++03 中的相应段落类似,只是重新措辞以适应从“序列点”到“被排序”的概念变化:
C++0x FDIS section 1.9 "Program Execution" §15 is similar to the corresponding paragraph in C++03, just reworded to accommodate the conceptual change from "sequence points" to "being sequenced":
这是未指定的。 C 和 C++ 在选择序列点时遵循相同的逻辑:
https://en.wikipedia.org/wiki/序列_点
It is unspecified. C and C++ follow the same logic in selecting sequence points:
https://en.wikipedia.org/wiki/Sequence_point
对于 C:“操作顺序不是由语言定义的。如果编译器能够保证一致的结果,编译器可以自由地以任何顺序计算此类表达式。” [...]“只有顺序求值 (,)、逻辑与 (&&)、逻辑或 (||)、条件表达式 (?:) 和函数调用运算符构成序列点,并且因此保证其操作数的特定求值顺序。”
来源:http://msdn.microsoft.com/en-us/library/ 2bxt6kc4.aspx
在那篇文章中的组织方式,似乎表明这也适用于 C++,这个问题的答案证实了这一点:运算符优先级与计算顺序。
For C: "Order of operations is not defined by the language. The compiler is free to evaluate such expressions in any order, if the compiler can guarantee a consistent result." [...] "Only the sequential-evaluation (,), logical-AND (&&), logical-OR (||), conditional-expression (? :), and function-call operators constitute sequence points and therefore guarantee a particular order of evaluation for their operands."
Source: http://msdn.microsoft.com/en-us/library/2bxt6kc4.aspx
The way this is organized in that article, it seems to indicate this applies to C++ too, which is confirmed by the answer to this question: Operator Precedence vs Order of Evaluation.
根据现行的C标准,C11 ,它还指定子表达式(本例中为
a
和b
)的求值顺序是不确定的。事实上,如果多次计算同一表达式,则该顺序甚至不必相同。来自第 6.5 节:
According to the current C standard, C11, it also specifies that the order of evaluation of subexpressions (
a
andb
in this case) is indeterminate. In fact, this order doesn't even have to be the same if the same expression is evaluated multiple times.From section 6.5: