3

Is the behavior of the code from this question expected?

Why does this go into an infinite loop?

Community
  • 1
  • 1
TJR
  • 3,617
  • 8
  • 38
  • 41
  • It's obvious from the link isn't it? It's not a bug or a feature, call it whatever but it's *documented*. Yup expected. – nawfal Jul 20 '14 at 09:07

1 Answers1

7

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.

Community
  • 1
  • 1
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • *"Evaluate Operands before Operation"* makes me think that it'll get the value from x on `++x` before increment, what's not what happens.. could you clarify this for me? – The Student Oct 01 '10 at 19:19
  • @Tom, it's `x++`. It does get the original value. If you do `x = 0; x = x++;`, the `x++` (the right operand of the assignment operator) fully evaluates before the assignment, so x is momentarily set to 1. But the result of the evaluation is 0 (the original value), and that is then assigned to `x`. – Matthew Flaschen Oct 01 '10 at 19:44
  • If it is specified that Evaluate Operands before Operation, then it should be for both ++x and x++; or there's a specification for each one? This is not clear for me.. – The Student Oct 01 '10 at 20:19
  • @Tom, Evaluate Operands before Operation applies for all operators (except `&&`, `||`, and `? :`). However, the right operand of x = `++x` is `++x`, not `x`. If you had `x = 0; x = ++x`, `++x` would still be evaluated before the assignment operator. However, in that case `++x` would evaluate to the new (incremented) value, so x would get set to 1. – Matthew Flaschen Oct 01 '10 at 20:42