Is the behavior from (other question) a bug or expected from the JVM spec?
Is the behavior of the code from t开发者_运维知识库his question expected?
Why does this go into an infinite loop?
I'm glad you asked, because few people at the other question attempted to explain why it was that way (plodoc's answer was probably closest). The most important part is:
§15.7.2 Evaluate Operands before Operation:
"The Java programming language also guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed."
The =
here is the Simple Assignment Operator = (§15.26.1)
It also guarantees the left operand will be evaluated first (§15.7.1), but the left hand side is trivial in this case.
This means the x++
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 x
's old value.
Finally, "old x" will be stored in x when the assignment operator is evaluated.
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).
It's also not a question of precedence. ++
has higher precedence than =
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.
精彩评论