0
int x = 12;     
int y = 15;      
while (y >= 0)     
{      
     x = x--;     
     y = --y;     
}      
System.out.print(x);     

This prints out 12 and I'm guessing x is never changed because it's stored before the post (x--) takes effect, but why does x-- never take effect?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Oscar F
  • 323
  • 2
  • 9
  • 21

2 Answers2

1

-- in x-- does take effect. However, you do not see it, because you assign the value of pre-decrement x right back into x.

Here is what happens when you do x = x--:

  • The value of x gets stored into a temporary space (say, tempX)
  • One is subtracted from x
  • New value is assigned back into x
  • Once the right-hand side has finished computing, tempX is assigned back to x

This produces the overall effect of x not being changed.

The effect of y = --y differs because the value of the expression --y is the same as the value of y after the decrement, so the overall effect is the same as --y.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Put simply, x = x--; does the following:

  1. Load variable x to the operand stack (value is 12).
  2. Decrement x, its value is now 11.
  3. Store the value loaded in step 1 back to x ==> x goes back to 12.
M A
  • 71,713
  • 13
  • 134
  • 174