What is x after "x = x++"?
What happens (behind the curtains) when this is executed?
int x = 7;
x = x++;
That is, when a variable is post incremented and assigned to itself in one statement? I compiled and executed this. x
is still 7 even after the entire statement. In my book, it says that x
is incremented!
Solution 1:
x = x++;
is equivalent to
int tmp = x;
x++;
x = tmp;
Solution 2:
x
does get incremented. But you are assigning the old value of x
back into itself.
x = x++;
-
x++
incrementsx
and returns its old value. -
x =
assigns the old value back to itself.
So in the end, x
gets assigned back to its initial value.
Solution 3:
The statement:
x = x++;
is equivalent to:
tmp = x; // ... this is capturing the value of "x++"
x = x + 1; // ... this is the effect of the increment operation in "x++" which
// happens after the value is captured.
x = tmp; // ... this is the effect of assignment operation which is
// (unfortunately) clobbering the incremented value.
In short, the statement has no effect.
The key points:
The value of a Postfix increment/decrement expression is the value of the operand before the increment/decrement takes place. (In the case of a Prefix form, the value is the value of the operand after the operation,)
the RHS of an assignment expression is completely evaluated (including any increments, decrements and/or other side-effects) before the value is assigned to the LHS.
Note that unlike C and C++, the order of evaluation of an expression in Java is totally specified and there is no room for platform-specific variation. Compilers are only allowed to reorder the operations if this does not change the result of executing the code from the perspective of the current thread. In this case, a compiler would be permitted to optimize away the entire statement because it can be proved that it is a no-op.
In case it is not already obvious:
- "x = x++;" is almost certainly a mistake in any program.
- The OP (for the original question!) probably meant "x++;" rather than "x = x++;".
- Statements that combine auto inc/decrement and assignment on the same variable are hard to understand, and therefore should be avoided irrespective of their correctness. There is simply no need to write code like that.
Hopefully, code checkers like FindBugs and PMD will flag code like this as suspicious.