Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of operations in i=i++; [duplicate]

Tags:

java

operators

Understanding the difference between ++i and i++, the below example still feels counter-intuitive.
Could someone please explain the order of operations and assignments in the following example?

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

Namely on line two, why is i not incremented after the assignment?

like image 273
Etheryte Avatar asked Jun 03 '14 14:06

Etheryte


People also ask

What are the 4 steps of order of operations?

First, we solve any operations inside of parentheses or brackets. Second, we solve any exponents. Third, we solve all multiplication and division from left to right. Fourth, we solve all addition and subtraction from left to right.

What is the correct order for the order of operations?

We can remember the order using PEMDAS: Parentheses, Exponents, Multiplication and Division (from left to right), Addition and Subtraction (from left to right).

Do I add or multiply first?

In particular, multiplication is performed before addition regardless of which appears first when reading left to right. For example, in 2 + 3 × 10, the multiplication must be performed first, even though it appears to the right of the addition, and the expression means 2 + 30.


1 Answers

The simple way to see it is like this:

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

i = 0

Then we come to the i = i++; line, where things get interesting. The right-hand side of the = is evaluated, and then assigned to the left-hand side. So let's look at the right-hand side of that, i++, which has two parts:

Step 2:

temporary_holder_for_value = i

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

Step 3:

i = i + 1

Now we're done with the right-hand side, and we assign the result to the left-hand side:

Step 4:

i = temporary_holder_for_value

The key is that last step. Basically, everything to the right of the = is done first, and the result of it is then assigned to the left. Because you used a post-increment (i++, not ++i), the result of the expression on the right takes i's value before the increment. And then the last thing is to assign that value to the left-hand side.

like image 96
T.J. Crowder Avatar answered Sep 20 '22 20:09

T.J. Crowder