Difference between i = ++i and ++i [duplicate]

五迷三道 提交于 2019-11-28 07:13:23

问题


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.


回答1:


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 :)




回答2:


Writing i = ++i; writes to variable i 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 to i = i + 1, as i = i + 2 (this actually makes sense in certain pipeline- and cache-related circumstances), or as format C:\ (silly, but technically allowed by the standard).




回答3:


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




回答4:


If i is of scalar type, then i = ++i is UB, and ++i is equivalent to i+=1. if i is of class type and there's an operator++ overloaded for that class then i = ++i is equivalent to i.operator=(operator++(i)), which is NOT UB, and ++i just executes the ++ operator, with whichever semantics you put in it.




回答5:


The result for the first one is undefined.




回答6:


These expressions are related to sequence points and, the most importantly, the first one results in undefined behavior.



来源:https://stackoverflow.com/questions/3914315/difference-between-i-i-and-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!