为什么 C/C++ 没有定义表达式求值顺序?

发布于 2024-07-30 20:18:26 字数 45 浏览 1 评论 0原文

您可能知道,C/C++ 没有指定表达式求值顺序。 未定义它们的原因是什么?

As you may know C/C++ does not specified expression evaluation order. What are the reasons to left them undefined.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你不是我要的菜∠ 2024-08-06 20:18:39

C/C++ 设计目标之一是编译器的高效实现。 因此,编译器可以相对自由地选择复杂表达式中各个子表达式的求值顺序; 这个顺序并不像我们想象的那样受到运算符优先级和结合性的限制。 在这种情况下,当我们在多个子表达式中修改相同的变量时,行为变得不可抗拒。 不保证在放弃前一个值之后且在计算表达式的任何其他部分之前立即执行递增或递减操作。 唯一的保证是更新将在表达式被视为完成之前执行。

未定义的行为意味着未定义,任何事情都可能发生

来源:Steve Summit 的 C 编程常见问题解答

One of the C/C++ design goals is the efficient implementation for complilers. So the compilers are given relatively free rein in choosing the evaluation order of various subexpression within a complicated expression; this order is not constrained by operator precedence and associativity as we think. In such situation when we a modifying the same vairiable in multiple sub expression, the behaviour become undefied. An increment or decrement operation is not guaranteed to be performed immediately after giving upthe previous value and before any other part of the expression is evalauted. The only guarantee is that the update will be performed before the expression is considered finished.

Undefined behavious means undefined and anything can happen.

Source:C programmig FAQ by Steve Summit

岁月如刀 2024-08-06 20:18:36

它允许编译器优化。
一个例子是对算术指令进行重新排序,以最大限度地利用 ALU 或通过计算隐藏内存延迟。

It allows compiler optimizations.
One example would be the reordering of arithmetic instructions for the maximum usage of the ALUs or hiding memory latency with calculations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文