What is x after “x = x++”?

后端 未结 17 1354
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 06:26

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

17条回答
  •  失恋的感觉
    2020-11-21 06:47

    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.

提交回复
热议问题