Dangling else

From Wikipedia, the free encyclopedia

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 this:

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
}

This is a problem that often comes up in compiler construction. It can be solved either at the implementation level, by telling the parser the right way to solve the ambiguity, or at the grammar level by using a Parsing expression grammar or equivalent.

Another way to solve it is to design the language to have a "end if" so the problem is eliminated. Examples of such languages are ALGOL 68 and Ada

Languages