In C operation associativity is as such for increment, decrement and assignment.
2. postfix ++ and --
3. prefix ++ and --
16. Direct assignment =
The full list is found here Wikipedia Operators in C
My question is when we have
int a, b;
b = 1;
a = b++;
printf("%d", a); // a is equal to 1
b = 1;
a = ++b;
printf("%d", a); //a is equal to 2
Why is a equal to 1 with b++ when the postfix increment operator should happen before the direct assignment?
And why is the prefix increment operator different than the postfix when they are both before the assignment?
I'm pretty sure I don't understand something very important when it comes to operation associativity.
The postfix operator a++
will increment a
and then return the original value i.e. similar to this:
{ temp=a; a=a+1; return temp; }
and the prefix ++a
will return the new value i.e.
{ a=a+1; return a; }
This is irrelevant to the operator precedence.
(And associativity governs whether a-b-c
equals to (a-b)-c
or a-(b-c)
.)