Subtopic 3 of 4
3.3Removing ambiguity: precedence and associativity
Use a separate non-terminal per precedence level (lower precedence nearer the start symbol). Left-recursive rule ⇒ left-associative, right-recursive ⇒ right-associative (e.g. ^ and =).
E
E
T
F
num 2
+
T
T
F
num 3
*
F
num 4
- F → num: 2
- T → F: 2
- E → T: 2
- F → num: 3
- T → F: 3
- F → num: 4
- T → T * F: 3 × 4 = 12
- E → E + T: 2 + 12 = 14
E → E + T | T, T → T * F | F: * binds tighter because it is deeper in the grammar, and left recursion makes + and * left-associative. Only one tree exists.
Previous year questions: Grammars, Derivations & FIRST/FOLLOW (8)
PYQs are grouped by topic, so this is the full set for Grammars, Derivations & FIRST/FOLLOW; try the ones that match this subtopic. Open all 8 on the topic page.