The key here is the table in "1.4 expressions" and "7.3.1 operator precedence and associativity." I will not duplicate the table from 1.4, but to indicate 7.3.1:
- With the exception of assignment operators, all binary operators are left-associative, which means that operations are performed from left to right correctly. For example, x + y + z is evaluated as (x + y) + z.
- assignment operators and a conditional operator (? :) are right-associative, which means that operations are performed with left. For example, x = y = z is evaluated as x = (y = z).
The first is logically expanded (or: uses the rules of associativity) as:
i = i + ++i;
here the order (from the table) is a preliminary increment, then an addition, then an assignment - so we should expect me to double plus one. And indeed, with i=6 we get 13 as expected.
a[++i] = i;
again from the table, the order should be access to the array, pre-increment, assignment - so I would expect that I + 1'th value would be me + 1. And really, check:
int[] a = { 0, 0, 0, 0, 0 }; int i = 2; a[++i] = i;
we really get {0, 0, 0, 3, 0} .
At the last method call, it takes precedence over subtraction, then it is from left to right; therefore it should be fun() , gun() , - , assignment.
Marc gravell
source share