Reputation: 1484
So I have always been taught that in Java, using the increment operator after a variable name in an expression will do the expression, and then increment the value and using the operator before a variable name in an expression will do the increment before the evaluation. Like this:
int x = 0;
int y = x++;
after this executes y should be 0 and x should be 1. and in this example
int x = 0;
int y = ++x;
should be x = 1 and y = 1.
Following that same logic, the following...
int x = 0;
int y = 0;
x = y++ - y++;
should output 0 as x and 2 as y because 0 - 0 = 0. However the output is
x = -1
y = 2
Why is this?
Edit: the value of y does not matter. x will always equal -1 and y will (in the end) equal y + 2.
Upvotes: 0
Views: 260
Reputation: 1518
Looks like all you assumptions are incorrect. In your first case
int x = 0;
int y = x++;
x is 0 and y is 1 because y takes the incremented value of x. Similarly for your second case x is 0 and y is 1. For your final case:
int x = 0;
int y = 0;
x = y++(y is 1 here) - y++(y is 2 now);
so here y++, makes y 1 then you subtract this 1 with another increment of y than makes y 2 at that point so x = 1-2= -1
Upvotes: 0
Reputation: 878
I was taught that when there was a variable++ it always happened after the statement was done.
Not after the statement, but rather after the expression.
Any time you have n - (n + 1)
you get the result -1
. The right-hand side of an assignment must be fully evaluated before the assignment can take place.
Upvotes: 0
Reputation: 44813
x = y++ - y++;
equals
int a = 0;
int b = 0;
int c = 0;
a = y++; // 0
b = y++; // 1
c = y;
-1 = a - b;
2 = y;
Upvotes: 0
Reputation: 279870
int x = 0;
int y = 0;
x = y++ - y++;
x = (0) - (1)
y = 1 ---> 2 // after ++
So x = -1
and y = 2
Upvotes: 2