3

Possible Duplicate:
Decrement in java

I was looking at this question, Decrement in Java and it piqued my curiosity. I understand how post/pre increment/decrement work, but I want to know why it works the way it does in that particular situation.

For example,

int x = 5;
x--;

Will very obviously set x to be 4. But if you do,

x = x--;

x will be 5 still (as discovered by the poster of the referenced question). From my understanding of post decrement, it returns the value before it modifies it. So what I expect to happen would be that x = 5 happens first. (keeping consistent with the above). Then, x is decremented, so in my mind, x--; would run, which in the above clearly sets x to be 4.

I mean, yes, it's easy enough just to do x--; but I would like to understand why Java's post decrement works this way.

I tried the code below and it worked exactly as expected.

int x = 5;
int y = x--;

y was set to 5 and x was properly decremented. Why doesn't the same happen for x = x--;?

Community
  • 1
  • 1
Sephallia
  • 396
  • 2
  • 9
  • 2
    As explained in [this answer](http://stackoverflow.com/a/11086829/829571). – assylias Jun 18 '12 at 17:25
  • This is similar to, but asking more detail from that question. – BlackVegetable Jun 18 '12 at 17:26
  • @assylias That is actually exactly what I was looking for! I can't believe I didn't look at that answer. I think I'm too used to looking at the top answers. I thought that `x = x--;` would rather be `int tmp = x; x = tmp; x--;` I had the order switched. – Sephallia Jun 18 '12 at 17:28

0 Answers0