运算符优先级,哪个结果是正确的?

发布于 2024-10-30 15:41:35 字数 333 浏览 4 评论 0 原文

可能的重复:
未定义的行为和序列点

此代码后的x的值是多少?

int x = 5;
x = ++x + x++;

在Java中,结果是12,但在C++中,结果是13。

我用google搜索了Java和C++的运算符优先级,它们看起来是一样的。那么为什么结果不同呢?是编译器的原因吗?

Possible Duplicate:
Undefined behavior and sequence points

What is the value of x after this code?

int x = 5;
x = ++x + x++;

In Java, the result is 12, but in C++, the result is 13.

I googled the operator precedence of both Java and C++, and they look the same. So why are the results different? Is it because of the compiler?

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

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

发布评论

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

评论(3

森末i 2024-11-06 15:41:35

在 Java 中,它的计算结果被定义为 12。它的计算结果如下:

x = ++x + x++;
x = 6 + x++; // x is now 6
x = 6 + 6; // x is now 7
x = 12 // x is now 12

+ (++x) 的左操作数在右操作数之前完全计算,这是由于 首先计算左手操作数。另请参阅之前的答案,和这个,关于类似的主题,并包含指向标准的链接。

在 C++ 中,这是未定义的行为,因为您在没有插入序列点。

In Java it's defined to evaluate to 12. It evaluates like:

x = ++x + x++;
x = 6 + x++; // x is now 6
x = 6 + 6; // x is now 7
x = 12 // x is now 12

The left operand of the + (++x) is completely evaluated before the right due to Evaluate Left-Hand Operand First. See also this previous answer, and this one, on similar topics, with links to the standard.

In C++, it's undefined behavior because you're modifying x three times without an intervening sequence point.

不乱于心 2024-11-06 15:41:35

运算符优先级控制如何将操作数分组在一起以计算结果。它不一定控制应用副作用的顺序。

在 C++ 中,++ 运算符都将在 + 运算符之前计算(尽管这只在 ++x 中有所不同,因为x++ 的值与 x 相同)。在 C++ 中,递增 x 的副作用发生在下一个序列点之前,这就是我们所能说的,并且该表达式中唯一的序列点是在它被完全求值之后,包括赋值。此外,根据标准,在序列点之间多次修改对象的结果是明确未定义的。

给定未定义的行为,典型的实现将执行一些操作,具体取决于实现序列如何定义行为的详细信息,因此,如果您坚持使用一个编译器的一个版本,通常会获得一致的结果。

Operator precedence governs how operands are grouped together for calculating the result. It doesn't necessarily govern the order of applying side effects.

In C++, the ++ operators will both be calculated before the + operator (although this only makes a difference in the ++x, because the value of x++ is the same as x). The side effect of incrementing x happens before the next sequence point in C++, and that's all we can say, and the only sequence point in that expression is after it is completely evaluated, including the assignment. Further, the result of modifying an object more than once between sequence points is explicitly undefined according to the Standard.

Given undefined behavior, the typical implementation will do something that depends on the details of how the implementation sequences defined behavior, and so you will often get a consistent result if you stick to one version of one compiler.

迷荒 2024-11-06 15:41:35

这是 C++ 中未定义的行为。见标准5.4。

It is undefined behaviour in C++. See 5.4 in the standard.

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