GATE / CS ARCHIVE

GATE CSE 1996 / QUESTION 2.10

Ambiguity from a dangling else

Compiler Design · Parsing & Syntax Analysis · Full GATE CSE 1996 paper

GATE 1996, Q2.10 2 marks · MCQ
Report issue

Parsing & Syntax Analysis

Question 2.10, GATE 1996: For stmt→if id then stmt | if id then stmt else stmt | id:=id, which listed nested-if statement is ambiguous?
Tap to enlarge
Your answer
Answer & solution

Answer: D: the nested-if statement with one dangling else (no official key was published)

An else following two unfinished nested if statements can attach either to the inner if or to the outer if. These choices produce different parse trees under the given grammar: if p then (if q then s else t), versus if p then (if q then s) else t. Both yield the same token sequence. The nested statement in D has precisely this form. A language implementation may impose “else matches the nearest if,” but that extra convention does not remove ambiguity from the grammar as printed.

Original paper, page 5