Dangling else

The dangling else is a problem in programming of parser generators in which an optional else clause in an if–then(–else) statement can make nested conditional statements ambiguous. Formally, the reference context-free grammar of the language is ambiguous, meaning there is more than one correct parse tree.

In many programming languages, one may write conditionally executed code in two forms: the if-then form, or the if-then-else form. (The else clause is optional.):

if a then s
if b then s1 else s2

Ambiguous interpretation becomes possible when there are nested statements; specifically when an if-then-else form replaces the statement s inside the above if-then construct:

if a then if b then s1 else s2

In this example, s1 gets executed if and only if a is true and b is true. But what about s2? One person might be sure that s2 gets executed whenever a is false (by attaching the else to the first if), while another person might be sure that s2 gets executed only when a is true and b is false (by attaching the else to the second if). In other words, someone could interpret the previous statement as being equivalent to either of the following unambiguous statements:

if a then { if b then s1 } else s2
if a then { if b then s1 else s2 }

The dangling-else problem dates back to ALGOL 60,[1] and subsequent languages have resolved it in various ways. In LR parsers, the dangling else is the archetypal example of a shift-reduce conflict.

  1. ^ Abrahams, P. W. (1966). "A final solution to the Dangling else of ALGOL 60 and related languages". Communications of the ACM. 9 (9): 679–682. doi:10.1145/365813.365821. S2CID 6777841.

From Wikipedia, the free encyclopedia · View on Wikipedia

Developed by Nelliwinne