(e-mail address removed), India said:
Consider the following code fragment:
int x = 4;
int y = 5;
int z = 6;
int r = x - y - z;
printf("r is %d\n", r);
What would you expect to be printed?
Is it:
(a) -7
(b) 5
(c) something else
If you answered (a), try to work out why (b) is also plausible.
If you answered (b), try to work out why (a) is also plausible.
If you answered (c), come back when you're feeling better.
Which answer you get depends on the order in which the subtractions are
done. 4 - (5 - 6) is different to (4 - 5) - 6. Clearly, precedence
cannot answer this question, since subtraction obviously has the same
precedence as subtraction!
So we need another tool for discriminating between operators at the same
precedence level. That tool is 'associativity'. Left-to-right
associativity means "do the stuff on the left first, and use the
calculated result as input for the stuff on the right", and
right-to-left associativity means, of course, the opposite.