Ambiguity

2 min read Updated Fri Apr 24 2026 07:36:29 GMT+0000 (Coordinated Universal Time)

Property of a string or a grammar.

Ambiguous String

A string is ambiguous iff it has more than one derivation tree.

Unambiguous Grammar

A grammar is unambiguous iff every string has exactly one derivation tree.

Example: SaSb    abS → aSb\;|\;ab

Ambiguous Grammar

A grammar GG is ambiguous iff its not unambiguous (i.e. there exists a string in L(G)L(G) with multiple derivation trees). Ambiguity often arises due to operator precedence and associativity.

Some ambiguous grammars can be rewritten as an equivalent unambiguous grammar.

Associativity

Associativity defines how operators of the same precedence are grouped.

Left Associative

Grouping from left to right.

Right Associative

Grouping from right to left.

Precedence

Defines order of evaluation. For example, multiplication has higher precedence than addition.

When precedence is equal, associativity resolves ambiguity.

Examples:

  • Left associative
    532=(53)25 − 3 − 2 = (5 − 3) − 2

  • Right associative
    4^3^2 = 4324^{3^2}

Examples

Grammar of arithmetic

SS+S    SS    SS    S/S    (S)    aS → S+S\;|\;S-S\;|\;S*S\;|\;S/S\;|\;(S)\;|\;a is ambiguous because a+aaa + a - a has 2 possible leftmost derivations.

The above grammar can be made unambiguous, using precedence + associativity:

  • SS+TTS → S + T | T
  • TTFFT → T * F | F
  • F(S)aF → (S) | a

Precedence is defined for * and ++ using SS, TT and FF.

Dangling Else

Consider the grammar:

<stmt> →
    if (<expr>) <stmt>
  | if (<expr>) <stmt> else <stmt>
  | <other_stmt>

Example statement:

if (expr1) if (expr2) f(); else g();

Two interpretations:

if (expr1) {
    if (expr2) f();
}
else g();
if (expr1) {
    if (expr2) f();
    else g();
}

Programming languages usually adopt rule “else associates with the closest if.”