C++(C ?) 中变量的多次预递增操作

发布于 2024-09-18 15:44:13 字数 111 浏览 2 评论 0原文

为什么下面的代码可以在 C++ 中编译?

int phew = 53;
++++++++++phew ;

同样的代码在 C 中失败,为什么?

Why does the following compile in C++?

int phew = 53;
++++++++++phew ;

The same code fails in C, why?

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

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

发布评论

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

评论(2

凉薄对峙 2024-09-25 15:44:13

注意:两个缺陷报告 DR#637DR#222 对于理解下面的行为理由。


作为解释,在 C++0x 中存在值计算副作用。例如,副作用是分配,而值计算是确定左值所指的内容或从左值中读取值。请注意,C++0x 不再具有序列点,并且这些内容的措辞是“之前序列”/“之后序列”。并且据说

如果标量对象上的副作用相对于同一标量对象上的另一个副作用或使用同一标量对象的值的值计算是无序的,则行为是未定义的。

++v 等价于 v += 1,而 v += 1 等价于 v = v + 1(只不过 v 仅计算一次)。这会产生 ++ (v = v + 1),我将其写为 inc = inc + 1,其中 inc 指的是左值v = v + 1 的结果。

在 C++0x 中,++ ++v 不是未定义的行为,因为对于 a = b,赋值是在 b 和 a 的值计算之后、但在 a 的值计算之前排序的。赋值表达式。由此可见,v = v + 1 中的赋值在 inc 的值计算之前排序。 inc = inc + 1 中的赋值是在 inc 的值计算之后排序的。最后,这两个分配都会被排序,并且不存在未定义的行为。

Note: The two defect reports DR#637 and DR#222 are important to understand the below's behavior rationale.


For explanation, in C++0x there are value computations and side effects. A side effect for example is an assigment, and a value computation is determining what an lvalue refers to or reading the value out of an lvalue. Note that C++0x has no sequence points anymore and this stuff is worded in terms of "sequenced before" / "sequenced after". And it is stated that

If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

++v is equivalent to v += 1 which is equivalent to v = v + 1 (except that v is only evaluated once). This yields to ++ (v = v + 1) which I will write as inc = inc + 1, where inc refers to the lvalue result of v = v + 1.

In C++0x ++ ++v is not undefined behavior because for a = b the assignment is sequenced after value computation of b and a, but before value computation of the assignment expression. It follows that the asignment in v = v + 1 is sequenced before value computation of inc. And the assignment in inc = inc + 1 is sequenced after value computation of inc. In the end, both assignments will thus be sequenced, and there is no undefined behavior.

朕就是辣么酷 2024-09-25 15:44:13

这是因为在 C++ 中,预自增运算符返回一个左值,并且它要求其操作数是一个左值

++++++++++phew ; 解释为 ++(++(++(++(++phew))))

但是你的代码调用未定义行为,因为您试图在两个序列点

C 中,预自增运算符返回一个右值,并要求其操作数是一个左值。所以你的代码不能在 C 模式下编译。

That is because in C++ pre-increment operator returns an lvalue and it requires its operand to be an lvalue.

++++++++++phew ; in interpreted as ++(++(++(++(++phew))))

However your code invokes Undefined Behaviour because you are trying to modify the value of phew more than once between two sequence points.

In C, pre-increment operator returns an rvalue and requires its operand to be an lvalue. So your code doesn't compile in C mode.

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