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
.
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.
来源:https://stackoverflow.com/questions/3914315/difference-between-i-i-and-i