This:
int i = 0;
i += i++
Can be seen as you doing (the following is a gross oversimplification):
int i = 0;
i = i + i; // i=0 because the ++ is a postfix operator and hasn't been executed
i + 1; // Note that you are discarding the calculation result
What actually happens is more involved than that - take a look at MSDN, 7.5.9 Postfix increment and decrement operators:
The run-time processing of a postfix increment or decrement operation of the form x++ or x-- consists of the following steps:
Note that due to order of precedence, the postfix ++
occurs before +=
, but the result ends up being unused (as the previous value of i
is used).
A more thorough decomposition of i += i++
to the parts it is made of requires one to know that both +=
and ++
are not atomic (that is, neither one is a single operation), even if they look like they are. The way these are implemented involve temporary variables, copies of i
before the operations take place - one for each operation. (I will use the names iAdd
and iAssign
for the temporary variables used for ++
and +=
respectively).
So, a closer approximation to what is happening would be:
int i = 0;
int iAdd = i; // Copy of the current value of i, for ++
int iAssign = i; // Copy of the current value of i, for +=
i = i + 1; // i++ - Happens before += due to order of precedence
i = iAdd + iAssign;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…