按位或保证求值顺序吗?
假设我有这段代码:
unsigned int func1();
unsigned int func2();
unsigned int func3();
unsigned int x = func1() | func2() | func3();
C++ 是否保证首先调用 func1(),然后调用 func2(),然后调用 func3()?
或者编译器是否允许以任意顺序调用函数?
另外,如果编译器愿意的话,是否允许在这里实现短路优化? (例如,如果 func1() 返回 ~0,编译器是否可以决定不再调用 func2() 或 func3(),因为它知道它们的返回值不可能影响分配给 x 的值?)
Say I have this code:
unsigned int func1();
unsigned int func2();
unsigned int func3();
unsigned int x = func1() | func2() | func3();
Does C++ guarantee that func1() will be called first, then func2(), and then func3()?
Or is the compiler allowed to call the functions in any order it feels like?
Also, is the compiler allowed to implement a short-circuit optimization here if it wants to? (e.g. if func1() returned ~0, could the compiler decide not to bother calling func2() or func3(), because it knows their return values can't possibly affect the value assigned to x?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,不能保证函数将以哪种顺序调用。与
||
不同,|
并不暗示序列点。必须调用表达式中的所有函数,除非实现可以确定它们没有副作用并且可以确定表达式的结果而不实际调用其中一个函数。该实现可以在“好像”规则下执行此操作,该规则允许实现执行符合程序无法观察或检测到的任何优化。
No, there is no guarantee which order the functions will be called in. Unlike
||
,|
does not imply a sequence point.All functions in the expression must be called unless the implementation can determine that they have no side-effects and it can determine the result of the expression without actually calling one of the functions. The implementation can do this under the "as if" rule which allows the implementation to perform any optimization which cannot be observed or detected by a conforming program.
它不会短路。它可能会无序执行。
“求值方向不会影响在同一级别包含多个乘法 (*)、加法 (+) 或二进制按位 (& | ^) 运算符的表达式的结果。”
It will not short circuit. It may execute out of order.
"The direction of evaluation does not affect the results of expressions that include more than one multiplication (*), addition (+), or binary-bitwise (& | ^) operator at the same level."