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 =?
java beginner, operator precedence table
155 views Asked by nrtn93 AtThere are 3 answers
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.
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, incrementinga
, 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 tob
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
tob
- the expression evaluates to the assigned value
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:
++
: Incrementa
.++
: Yield the old value ofa
.=
: Assign the old value ofa
tob
.It's equivalent to this code.