Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The statement:</p> <pre><code>x = x++; </code></pre> <p>is equivalent to:</p> <pre><code>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. </code></pre> <p>In short, the statement has no effect.</p> <p>The key points: </p> <ul> <li><p>The value of a Postfix increment/decrement expression is the value of the operand <em>before</em> the increment/decrement takes place. (In the case of a Prefix form, the value is the value of the operand <em>after</em> the operation,)</p></li> <li><p>the RHS of an assignment expression is completely evaluated (including any increments, decrements and/or other side-effects) <em>before</em> the value is assigned to the LHS.</p></li> </ul> <p><sub>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.</sub></p> <hr> <p>In case it is not already obvious:</p> <ul> <li>"x = x++;" is almost certainly a mistake in any program.</li> <li>The OP (for the original question!) probably meant "x++;" rather than "x = x++;".</li> <li>Statements that combine auto inc/decrement and assignment on the same variable are hard to understand, and <em>therefore</em> should be avoided <em>irrespective of their correctness</em>. There is simply no need to write code like that. </li> </ul> <p>Hopefully, code checkers like FindBugs and PMD will flag code like this as suspicious.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload