java beginner, operator precedence table

162 views Asked by At

I look at the operator precedence table and ++ operator comes before = operator. But to compute this expression, b=a++; first, a is assigned to b and then a is incremented. This is confusing. Which one comes first, ++ or =?

3

There are 3 answers

3
rgettman On BEST ANSWER

Yes, ++ has higher precedence than =. But you need to think of the ++ post-increment operator as 2 operations -- increment the variable and yield the old value -- that happen before the operator with lower precedence, =.

Here is what happens:

  1. Post-increment Operator ++: Increment a.
  2. Post-increment Operator ++: Yield the old value of a.
  3. Operator =: Assign the old value of a to b.

It's equivalent to this code.

int resultOfPostIncrement = a;
a = a + 1;
b = resultOfPostIncrement;
0
Tagir Valeev On

You can read, for example this tutorial which says that increment/decrement operators have the highest precedence, while assignment operators have the lowest precedence. Thus in your example first a++ will be executed, then the previous value of a will be assigned to b.

Note that you cannot change the precedence in your case even using the parentheses: (b=a)++ is the compilation error.

1
Joffrey On

As opposed to what many people seem to think, b is NOT assigned before incrementing a when we write int b = a++;. It is assigned the former value of a, but later in the timeline than the actual increment of a.

Therefore, it does not contradict what precedence tells you.


To convince you, here is a little example that convinced me:

int a = 1;
int b = a++ + a++;

At the end, b equals 3, not 2, and a is also 3. What happens because of precedence is:

  • the left a++ is evaluated first, incrementing a, but still evaluated to the former value 1 by definition of the operator
  • the right a++ is evaluated, reading the new value 2 (proving that the first increment already happened), incrementing it to 3, but still evaluating to 2
  • the sum is calculated 1 + 2, and assigned to b

This is because you should see a++ as both an instruction and an expression.

  • the instruction increments a
  • the expression evaluates to the former value of a

It's the same kind of things as in b = a, which also is an instruction and an expression:

  • the instruction assigns the value of a to b
  • the expression evaluates to the assigned value