简体   繁体   中英

java weird increment syntax

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.

int x = 0;
int y = 0;
x = y++ - y++;
x = (0) - (1)
y = 1 ---> 2 // after ++

So x = -1 and y = 2

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;

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM