Reputation: 2884
I read a few post regarding unary operator: What is the Difference between postfix and unary and additive in java "C - C++" joke about postfix/prefix operation ordering
And a few more.
However, I still don't understand exactly when the value is changed.
For example:
int x = 1;
x = x++;
System.out.print("x = x++ ==> ");
System.out.print(" x = " + x);
System.out.println();
int x = 1;
x = x++ + x++;
System.out.print("x = x++ + x++ ==> ");
System.out.print(" x = " + x);
System.out.println();
The output is:
x = x++ ==> x = 1
x = x++ + x++ ==> x = 3
So in the first block x
is assigned to x
and afterwards incremented, but the value is never used, otherwise the output would have been x = 2
.
In the second block, if I understand correctly, the first x++
is evaluated before the assignment and the second x++
is evaluated afterwards but is never used.
If in the second block both x++
would have been evaluated after the assignment but never used, the output would have been x = 2
. If both have been used, the output would have been x = 4
.
My IDE also indicated that the first x++
is used, but the second is not used:
So to conclude - I'm still confused about when and how exactly the increment is done.
Upvotes: 1
Views: 374
Reputation: 95968
At the line
x = x++ + x++;
Assuming x = 1
, the first x++
returns "1" as the value, and then it increments x
to 2. So basically, it's assigning the old value back to x
.
The second x++
does the same; it returns the value of x
, which is now 2, and only then increments its value to 3 - that value, is not used.
Your code is equivalent to:
tmp = x;
x = x + 1;
tmp2 = x;
x = x + 1; // not used
x = tmp + tmp2;
Links that may help you:
Upvotes: 3