Question

What is the "hanging else" problem? (Is that the right name?)

Following a C++ coding standard (forgot which one) I always use brackets (block) with control structures. So I don't normally have this problem (to which "if" does the last(?) else belong), but for understanding possible problems in foreign code it would be nice with a firm understanding of this problem. I remember reading about it in a book about Pascal many years ago, but I can't find that book.

Was it helpful?

Solution

Which if does the else belong to?

if (a < b)
    if (c < d)
        a = b + d;
    else
        b = a + c;

(Obviously you should ignore the indentation.)

That's the "hanging else problem".

C/C++ gets rid of the ambiguity by having a rule that says you can't have an-if-without-an-else as the if-body of an-if-with-an-else.

OTHER TIPS

Ambiguous else.

Some info here: http://theory.stanford.edu/~amitp/yapps/yapps-doc/node3.html

But the classic example is:

if a then
  if b then
     x = 1;
  else 
     y = 1;

vs.

if a then
  if b then
     x = 1;
else 
  y = 1;

Looking at this from a langauge design point of view.

The standard BNF-like grammar for if-else:

Statement :-   .. STUFF..
          |    IfStatement

IfStatement :- IF_TOKEN '(' BoolExpression ')' Statement IfElseOpt

IfElseOpt :-   /* Empty */
          |    ELSE_TOKEN Statement

Now from a parsers point of view:

if (cond1) Statement1
   if (cond2) Statement2
else Statement3

When you get to the ELSE_TOKEN the parser has two options, SHIFT or REDUCE. The problem is that which to choose requires another rule that the parser must follow. Most parsers generators default to SHIFT when given this option.

I don't see the problem for Pascal?

This one is incorrectly indented.

if a then
  if b then
     x = 1;
  else
     y = 1;

Removing the semi-colon from after x = 1 would make it correctly indented.

This one correctly indented

if a then
  if b then
     x = 1;
else
  y = 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top