+ 1
Why x!=3? In Java
int x=3;x+=x++; // In the end you have x ==2. Why? https://code.sololearn.com/cPFwT69FFOvM/?ref=app
3 Answers
+ 4
If I'm correct this behaviour is similiar to this one:
https://stackoverflow.com/questions/7911776/what-is-x-after-x-x
post increment means, it returns the value and then increment it.
x is 1 -> x += 1 -> x is 2 -> increment x but 2 is already assigned to x. So I would say the old value (2) overrides the new value (3)
So in the end you get x = 2
Another example:
int x = 1
int y = 1
x += y++
x uses the old value, so x gets 2, increment y, so y gets also 2
x = 1
x += ++x
In this case it increments x and then the value is added to x, so you get 3.
+ 2
Java operates a stack in addition to values in memory.
int x = 1;
x += x++;
After the first instruction, the value of x at its referenced location is 1.
The second instruction is an addition to x. So, throw x as summand onto the stack. What is added to x is x, throw x as second summand onto the stack, then increment x at its memory location. The increment happens AFTER the value of x is added onto the stack because it is a postincrement operator.
At this time, two 1s are on the stack, x in memory is 2 because of the increment.
Then perform the addition on the stack: 1+1=2. And assign the result to x at its memory location. Hence, x gets the value 2.
0
Yes, I think you are right. Tanks a lot!!!