Definitions

Dangling_else

Dangling else

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. Python solves this problem by requiring the nested if statements to be indented.

if foo:
    if bar:
        print 'Inner True'
    else:
        print 'Inner False'
else:
    print 'Outer False'

C and languages with similar syntax use braces to clearly define the body of the statement.

The problem can also be solved by removing the possibility for ambiguity, e.g. by designing the language to have an "end if". Examples of such languages are ALGOL 68, Ada, and REALbasic.

Search another word or see Dangling_elseon Dictionary | Thesaurus |Spanish
  • Please Login or Sign Up to use the Recent Searches feature
FAVORITES
RECENT