Associativity is only needed when the operators in an expression have the same precedence. Usually + and - have the same precedence. Consider the expression 7 - 4 + 2. The result could be either (7 - 4) + 2 = 5 or 7 - (4 + 2) = 1. The former result corresponds to the case when + and - are left-associative, the latter to when + and - are right-associative. In order to reflect normal usage,
addition,
subtraction,
multiplication, and
division operators are usually left-associative, while for an
exponentiation operator (if present) there is no general agreement. Any
assignment operators are typically right-associative. To prevent cases where operands would be associated with two operators, or no operator at all, operators with the same precedence must have the same associativity.
A detailed example Consider the expression 5^4^3^2, in which ^ is taken to be a right-associative exponentiation operator. A parser reading the tokens from left to right would apply the associativity rule to a branch, because of the right-associativity of ^, in the following way: • Term 5 is read. • Nonterminal ^ is read. Node: "5^". • Term 4 is read. Node: "5^4". • Nonterminal ^ is read, triggering the right-associativity rule. Associativity decides node: "5^(4^". • Term 3 is read. Node: "5^(4^3". • Nonterminal ^ is read, triggering the re-application of the right-associativity rule. Node "5^(4^(3^". • Term 2 is read. Node "5^(4^(3^2". • No tokens to read. Apply associativity to produce parse tree "5^(4^(3^2))". This can then be evaluated depth-first, starting at the top node (the first ^): • The evaluator walks down the tree, from the first, over the second, to the third ^ expression. • It evaluates as: 3 = 9. The result replaces the expression branch as the second operand of the second ^. • Evaluation continues one level up the
parse tree as: 4 = . Again, the result replaces the expression branch as the second operand of the first ^. • Again, the evaluator steps up the tree to the root expression and evaluates as: 5 ≈ . The last remaining branch collapses and the result becomes the overall result, therefore completing overall evaluation. A left-associative evaluation would have resulted in the parse tree ((5^4)^3)^2 and the completely different result (625) = ≈ . == Right-associativity of assignment operators ==