A grammar is ambiguous if a single string can have more than one parse tree (or derivation).
E → E + E | E * E | id
id + id * id
This string can be interpreted in two different ways:
(id + id) * id
id + (id * id)
E
/ | \
E * E
/|\ |
E + E id
| |
id id
E
/ | \
E + E
| /|\
id E * E
| |
id id
👉 Same input → Different meanings → ❌ Ambiguity
Associativity defines the order in which operators of the same precedence are evaluated.
👉 Evaluation from left to right
a - b - c
👉 Interpreted as:
(a - b) - c
+, -, *, /👉 Evaluation from right to left
a = b = c
👉 Interpreted as:
a = (b = c)
=)^)Precedence defines which operator is evaluated first when different operators appear together.
a + b * c
👉 Multiplication has higher precedence:
a + (b * c)
| Level | Operator | Meaning |
|---|---|---|
| High | ^ |
Power |
| Medium | *, / |
Multiply/Divide |
| Low | +, - |
Add/Subtract |
| Lowest | = |
Assignment |
E → E + E | E * E | id
E → E + T | T
T → T * F | F
F → id
* has higher precedence than +Ambiguity → Resolved by → Precedence + Associativity
a + b * c - d
* first → b * c+ and - left to right((a + (b * c)) - d)
👉 Frequently asked:
| Aspect | Ambiguity | Associativity | Precedence |
|---|---|---|---|
| Definition | Multiple parse trees | Order for same operators | Priority of operators |
| Purpose | Identify problem | Resolve order | Resolve priority |
| Example | id + id * id | a - b - c | a + b * c |
| Type | — | Left/Right | Levels |
| Role | Problem | Solution | Solution |
| Importance | Very High | Very High | Very High |
Open this section to load past papers