i = ++i 和 ++i 之间的区别
i = ++i;
和 ++i;
之间有什么区别,其中 i
是值为 10
的整数?
根据我的说法,两者都执行相同的递增 i
的工作,即在完成两个表达式 i =11
后。
Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
What is the difference between i = ++i;
and ++i;
where i
is an integer with value 10
?
According to me both do the same job of incrementing i
i.e after completion of both the expressions i =11
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
i = ++i;
调用未定义行为,而++i;
则不会。C++03 [第 5/4 节] 表示
在上一个和下一个序列点之间,标量对象的存储值最多应通过表达式的求值修改一次
。在
i = ++i
中,i
被修改了两次[预增量和赋值],没有任何中间序列点,因此该行为在 C 和 C++ 中都是未定义的。然而,
i = ++i
在 C++0x 中定义良好:)i = ++i;
invokes Undefined Behaviour whereas++i;
does not.C++03 [Section 5/4] says
Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression
.In
i = ++i
i
is being modified twice[pre-increment and assignment] without any intervening sequence point so the behaviour is Undefined in C as well as in C++.However
i = ++i
is well defined in C++0x :)编写
i = ++i;
会向变量i
写入两次(一次用于增量,一次用于赋值),而无需 两者之间的序列点。根据 C 语言标准,这会导致未定义的行为。这意味着编译器可以自由地将
i = ++i
实现为与i = i + 1
相同,如i = i + 2
(这实际上在某些与管道和缓存相关的情况下有意义),或者作为格式C:\(愚蠢,但技术上标准允许)。Writing
i = ++i;
writes to variablei
twice (one for the increment, one for the assignment) without a sequence point between the two. This, according to the C language standard causes undefined behavior.This means the compiler is free to implement
i = ++i
as identical toi = i + 1
, asi = i + 2
(this actually makes sense in certain pipeline- and cache-related circumstances), or asformat C:\
(silly, but technically allowed by the standard).i = ++i 通常(但不一定)给出
i = i 的结果;
我+1;
给出 i = 10
正如评论所指出的,这是未定义的行为,永远不应该依赖,
而 ++i 总是给出
i = i+1;
得出 i = 11;
因此这是正确的做法
i = ++i will often, but not necessarily, give the result of
i = i;
i +1;
which gives i = 10
As pointed out by the comments, this is undefined behaviour and should never be relied on
while ++i will ALWAYS give
i = i+1;
which gives i = 11;
And is therefore the correct way of doing it
如果i是标量类型,则
i = ++i
是UB,而++i
相当于i+=1
。如果 i 是类类型并且该类有一个重载的运算符++,那么
i = ++i
相当于i.operator=(operator++(i))
,它不是 UB,而++i
只是执行++ 运算符
,无论其语义如何。If i is of scalar type, then
i = ++i
is UB, and++i
is equivalent toi+=1
.if i is of class type and there's an operator++ overloaded for that class then
i = ++i
is equivalent toi.operator=(operator++(i))
, which is NOT UB, and++i
just executes the++ operator
, with whichever semantics you put in it.第一个的结果是未定义的。
The result for the first one is undefined.
这些表达式与 序列点 相关,最重要的是,第一个结果是 未定义行为。
These expressions are related to sequence points and, the most importantly, the first one results in undefined behavior.