后缀增量是否对返回值执行增量?
又是一个愚蠢的问题。
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int i = 0;
i = i++;
cout<<i;
return 0;
}
尽管我期望 0,但我得到 1
作为该程序的结果打印:首先创建一个等于 0 的临时对象,然后 i 递增,然后返回临时对象并将其分配给 i。就根据:
5.2.6 递增和递减 [expr.post.incr] 1 获得的值 通过应用后缀 ++ 是值 操作数在应用之前拥有的 操作员。 [注:数值 获得的是原件的副本 值]
我在 MS VC 2008 和 GCC 下检查了它。尽管至少 gcc 在增量字符串中发出警告,但它们给出了相同的结果。我哪里错了?
Again, a silly question.
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int i = 0;
i = i++;
cout<<i;
return 0;
}
I get 1
printed as a result of this program though I expected 0: first a temp object created eing equal 0, then i is incremented, then temp object is returned and assigned to i. Just according to:
5.2.6 Increment and decrement [expr.post.incr]
1 The value obtained
by applying a postfix ++ is the value
that the operand had before applying
the operator. [Note: the value
obtained is a copy of the original
value ]
I checked it under MS VC 2008 and GCC. They give both the same result, though at least gcc issues a warning in incrementation string. Where am I wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
的行为
是未定义的。如果单个表达式为变量分配两个不同的值,C++ 规范表示任何事情都可能发生 - 它可以采用旧值、两个新值之一或几乎任何东西。这样做的原因是它允许编译器对简单表达式进行更积极的优化。例如,如果编译器认为这样更有效,则可以重新排列赋值和
++
的执行顺序。The behavior of
is undefined. If a single expression assigns two different values to a variable, the C++ spec says that anything can happen - it could take on its old value, one of the two new values, or pretty much anything at all. The reason for this is that it allows the compiler to make much more aggressive optimizations of simple expressions. The compiler could rearrange the order in which the assignment and
++
are executed, for example, if it thought it were more efficient.