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

▼魔方 西西 提交于 2019-11-29 13:17:37

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

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

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

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.

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.

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