ArticleslgStudy

computer science

Dangling else

Dangling else is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Dangling else rather than just read about it. In short: 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.

Key takeaways

  • Dangling else belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Dangling else to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Dangling else from memory before moving on to harder problems.

Reference excerpt

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.

Description 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, and subsequent languages have resolved it in various ways. In LR parsers, the dangling else is the archetypal example of a shift-reduce conflict.

Examples Concrete examples follow.

C In C, the grammar reads, in part:

statement = ... | selection-statement

selection-statement = ... | IF ( expression ) statement | IF ( expression ) statement ELSE statement Thus, without further rules, the statement

could ambiguously be parsed as if it were either:

or:

The C standard clarifies that an else block is associated with the nearest if. Therefore, the first tree is chosen.

Approaches to avoid the issue

Avoiding ambiguity while keeping the syntax This problem often comes up in compiler construction, especially scannerless parsing. The convention when dealing with the dangling else is to attach the else to the nearby if statement, allowing for unambiguous context-free grammars, in particular. Programming languages like Pascal, C, and Java follow this convention, so there is no ambiguity in the semantics of the language, though the use of a parser generator may lead to ambiguous grammars. In these cases alternative grouping is accomplished by explicit blocks, such as begin...end in Pascal and {...} in C. Depending on the compiler construction approach, one may take different corrective actions to avoid ambiguity:

If the parser is produced by an SLR, LR(1), or LALR LR parser generator, the programmer will often rely on the generated parser feature of preferring shift over reduce whenever there is a conflict. Alternatively, the grammar can be rewritten to remove the conflict, at the expense of an increase in grammar size (see below). If the parser is hand-written, the programmer may use a non-ambiguous context-free grammar. Alternatively, one may rely on a non-context-free grammar or a parsing expression grammar.

Avoiding ambiguity by changing the syntax The problem can also be solved by making explicit the link between an else and its if, within the syntax. This usually helps avoid human errors. Possible solutions are:

Having an "end if" symbol delimiting the end of the if construct. Examples of such languages are ALGOL 68, Ada, Eiffel, PL/SQL, Visual Basic, Modula-2, and AppleScript. Disallowing the statement following a "then" to be an "if" itself (it may however be a pair of statement brackets containing only an if-then-clause). Some implementations of ALGOL 60 follow this approach. Requiring braces (parentheses) when an "else" follows an "if". Requiring every "if" to be paired with an "else". Using different keywords for the one-alternative and two-alternative "if" statements. S-algol uses if e do s for the one-alternative case and if e1 then e2 else e3 for the general case. Requiring braces unconditionally, like Swift and Rust. This is effectively true in Python as its indentation rules delimit every block, not just those in "if" statements.

Avoiding the conflict in LR parsers The above example could be rewritten in the following way to remove the ambiguity :

statement: open_statement | closed_statement ;

open_statement: IF '(' expression ')' statement | IF '(' expression ')' closed_statement ELSE open_statement ;

closed_statement: non_if_statement | IF '(' expression ')' closed_statement ELSE closed_statement ;

non_if_statement: ... ;

Any other statement-related grammar rules may also have to be duplicated in this way if they may directly or indirectly end with a statement or selection-statement non-terminal. However, we give grammar that includes both of if and while statements.

statement: open_statement | closed_statement ;

open_statement: IF '(' expression ')' statement | IF '(' expression ')' closed_statement ELSE open_statement | WHILE '(' expression ')' open_statement ;

closed_statement: simple_statement | IF '(' expression ')' closed_statement ELSE closed_statement | WHILE '(' expression ')' closed_statement ;

simple_statement: ... ;

Finally, we give the grammar that forbids ambiguous IF statements.

statement: open_statement | closed_statement ;

open_statement: IF '(' expression ')' statement | IF '(' expression ')' closed_statement ELSE open_statement | WHILE '(' expression ')' open_statement ;

closed_statement: simple_statement | IF '(' expression ')' closed_statement ELSE closed_statement | WHILE '(' expression ')' closed_statement ;

simple_statement: ... ;

With this grammar the statement if (a) if (b) c else d can only be parsed one way, because the other interpretation (if (a) {if (b) c} else d) is produced as

statement open_statement IF '(' expression ')' closed_statement ELSE open_statement 'if' '(' 'a' ')' closed_statement 'else' 'd'

and then the parsing fails trying to match closed_statement to "if (b) c". An attempt with closed_statement fails in the same way. The other parse, if (a) {if (b) c else d}) succeeds:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Dangling else

Start with the simplest possible case. Write down what Dangling else claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Dangling else before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Dangling else ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Dangling else

In research
Dangling else appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Dangling else in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Dangling else is common in secondary-school and first-year university syllabi. It links to neighbouring topics Ambiguity, Computer programming, Conditional constructs, so understanding it makes those chapters shorter.
In everyday life
Look for Dangling else outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Dangling else” →

How to study Dangling else in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Dangling else means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Dangling else out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Dangling else in simple terms?

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 pars…

Why does Dangling else matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Dangling else?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Dangling else.

Tags

  • Ambiguity
  • Computer programming
  • Conditional constructs
  • Parsing

Keep exploring