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 =?
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:
++
: Increment a
.++
: Yield the old value of a
.=
: Assign the old value of a
to b
.It's equivalent to this code.
int resultOfPostIncrement = a;
a = a + 1;
b = resultOfPostIncrement;