C++(C ?) 中变量的多次预递增操作
为什么下面的代码可以在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
注意:两个缺陷报告 DR#637和 DR#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
andside 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++v
is equivalent tov += 1
which is equivalent tov = v + 1
(except that v is only evaluated once). This yields to++ (v = v + 1)
which I will write asinc = inc + 1
, whereinc
refers to the lvalue result ofv = v + 1
.In C++0x
++ ++v
is not undefined behavior because fora = 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 inv = v + 1
is sequenced before value computation ofinc
. And the assignment ininc = inc + 1
is sequenced after value computation ofinc
. In the end, both assignments will thus be sequenced, and there is no undefined behavior.这是因为在
C++
中,预自增运算符返回一个左值
,并且它要求其操作数是一个左值
。++++++++++phew ;
解释为++(++(++(++(++phew))))
但是你的代码调用
未定义行为
,因为您试图在两个序列点。在
C
中,预自增运算符返回一个右值
,并要求其操作数是一个左值
。所以你的代码不能在 C 模式下编译。That is because in
C++
pre-increment operator returns anlvalue
and it requires its operand to be anlvalue
.++++++++++phew ;
in interpreted as++(++(++(++(++phew))))
However your code invokes
Undefined Behaviour
because you are trying to modify the value ofphew
more than once between two sequence points.In
C
, pre-increment operator returns anrvalue
and requires its operand to be anlvalue
. So your code doesn't compile in C mode.