Chapter 4:Syntax Analysis

Ambiguity

. Dangling else problem

Stmt if expr then stmt

| if expr then stmt else stmt

. according to this grammar, string if el then if e2 then S1 else S2 has two parse trees

The dangling else is a well-known problem in computer programming in which a seemingly well-defined grammar can become ambiguous. In many programming languages you can write code like if a then if b then s1 else s2 which can be understood in two ways:

Either as

if a then

if b then

s1

else

s2

or as

if a then

if b then

s1

else

s2

So, according to the following grammar, the string if el then if e2 then S1 else S2 will have two parse trees as shown in the next slide.

stmt if expr then stmt

| if expr then stmt else stmt

| other