Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm glad you asked, because few people at the other question attempted to explain <em>why</em> it was that way (<a href="https://stackoverflow.com/questions/3831341/why-does-this-go-into-an-infinite-loop/3832184#3832184">plodoc</a>'s answer was probably closest). The most important part is:</p> <p><a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.7.2" rel="nofollow noreferrer">§15.7.2</a> Evaluate Operands before Operation:</p> <blockquote> <p>"The Java programming language also guarantees that every operand of an operator (except the conditional operators &amp;&amp;, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed."</p> </blockquote> <p>The <code>=</code> here is the Simple Assignment Operator = (<a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.1" rel="nofollow noreferrer">§15.26.1</a>)</p> <p>It also guarantees the left operand will be evaluated first (<a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.7.1" rel="nofollow noreferrer">§15.7.1</a>), but the left hand side is trivial in this case.</p> <p>This means the <code>x++</code> must be evaluated before the assignment operator is evaluated. The increment will take place before the assignment, and since it's post-increment, it evaluates to <code>x</code>'s old value.</p> <p>Finally, "old x" will be stored in x when the assignment operator is evaluated.</p> <p>It is important to emphasize that this is not guaranteed in all languages regardless of what it does in your compiler, or how intuitive it seems (or not).</p> <p>It's also <em>not</em> a question of precedence. <code>++</code> has higher precedence than <code>=</code> in C and C++ too. But in those languages, modifying a variable twice between sequence points is undefined behavior. So fully compliant C compilers yield different results. </p>
 

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