The order of operations in i = i ++;

Understanding the difference between ++i and i++ , the example below still seems contradictory.
Can someone explain the order of operations and assignments in the following example?

  int i = 0; i = i++; System.out.println(i); // 0 

Namely, on the second line, why does i not increase after assignment?

+7
java operators
source share
1 answer

An easy way to see this is as follows:

Step 1: Your line int i = 0; which (of course) does this:

 i = 0 

Then we go to the line i = i++; where everything becomes interesting. Right side = estimated and then assigned to the left side. Therefore, consider the right side of this, i++ , which consists of two parts:

Step 2:

 temporary_holder_for_value = i 

The value of i read and stored in a temporary place (I expect one of the registers of the virtual machine). Then the second part of i++ is executed:

Step 3:

 i = i + 1 

Now we are done on the right side, and we assign the result to the left side:

Step 4:

 i = temporary_holder_for_value 

The key is the last step. In principle, everything to the right of = is executed first, and its result is then assigned to the left. Since you used post-increment ( i++ , not ++i ), the result of the expression on the right takes i value before the increment. And then the last thing is to assign this value to the left side.

+13
source share

All Articles