3

I'm reading Sams Teach Yourself Java and on the page about incrementing and decrementing the author says

  int x = 7;
  x = x++;

"In this example, the statement x = x++ increments the x variable from 7 to 8." However the output is not 8, but 7 when complied. (no surprise there)

But then why does x++; by itself give the output 8?

some random dude
  • 457
  • 1
  • 4
  • 11
  • 5
    Why in the world would anyone write `x = x++`... But anyways, `x++` is short for "return x, then increment x by 1". – awksp Jun 09 '14 at 03:24
  • I think that the author is expecting you to figure that out for yourself. Based on the stuff that you (should have) just read. – Stephen C Jun 09 '14 at 03:25
  • I think it has to do with when the assignment of x=x and x++ actually occurs – MadProgrammer Jun 09 '14 at 03:25
  • see http://stackoverflow.com/questions/19216118/how-is-that-x-20x-x-x-x-final-value-of-x-in-java-is-65#answer-19216199 – Sam Dufel Jun 09 '14 at 03:27
  • @user3580294 that should be simply the answer for this question – Baby Jun 09 '14 at 03:28
  • @ImmerAllein - it is a bit more complicated than that. See the explanations in the Questions I linked to. – Stephen C Jun 09 '14 at 03:31
  • @user3580294 The JLS takes a slightly different, and clearer view. `x++` has value the old value of `x`, and a side effect of incrementing `x` by 1. The whole thing is executed in the normal order, so in `x=x++;` the increment is done before the assignment, and overwritten by it. – Patricia Shanahan Jun 09 '14 at 03:37
  • @PatriciaShanahan Isn't that what I said? – awksp Jun 09 '14 at 03:56
  • @user3580294 The, admittedly subtle, difference is that the "return x, then increment" formulation suggests that the side effect happens after the value has been returned, creating ambiguity about what other actions happen before the side effect. That is what leads to undefined behavior in this area in C. The JLS formulation ensures that all work for the `++` operator is done in one chunk, clearly completed before the assignment. – Patricia Shanahan Jun 09 '14 at 04:01
  • @PatriciaShanahan That's a good point... I was intending for the "return x, then increment x by 1" be taken as a "single instruction", as it is, but I admit my wording is misleading. Thanks for the clarification! Interesting to learn that that is the reason behind the undefined behavior in C... Wonder why it wasn't cleared up later. Maybe to allow optimizations? I've heard optimizing compilers love undefined behavior – awksp Jun 09 '14 at 04:10

0 Answers0