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;
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:
a++ is evaluated first, incrementing a, but still evaluated to the former value 1 by definition of the operatora++ is evaluated, reading the new value 2 (proving that the first increment already happened), incrementing it to 3, but still evaluating to 21 + 2, and assigned to bThis is because you should see a++ as both an instruction and an expression.
aaIt's the same kind of things as in b = a, which also is an instruction and an expression:
a to bIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With