A problem in some programming languages where an else doesn't match the if it's intended to match.

if (x >= 0)
  if (x >= 100)
    x = x-100;
  return -1;
doSomethingElse (x);
The indentation would lead one to think that this code checks to see if x is greater than zero, if it is, checks again to see if it's over 100, if it is, subtract 100 if x was negative to begin with, return, and then do something to x. However, despite the indentation, that else associates with the second if, always returning if x is less than 100. The solution to the dangling else is the use of braces (or begin/end or whatever) to enforce the correct association.

if (x >=0) {
  if (x >= 100) {
    x = x - 100;
else {
  return -1;
doSomethingElse (x);
It's a Good Thing to use braces even when not needed to avoid this and other problems when you modify your code.

The dangling else "problem" is a fine example of how novice programmers know better than the language designers. Usually an unattributed story is added, of some PL/I compiler that actually depended on indentation rather than on the language definition to decide the issue.

There is, in fact, a minor problem in parsing a dangling else. yacc and friends will say that a "shift/reduce conflict" has been resolved. The standard way to resolve it actually DTRT, and the else matches the inner if.

The solution to the programmer's "dangling else" problem (as opposed to the compiler writer's "dangling else" non-problem) is to use an editor which does (correct) indentation for you, like (X)Emacs. That way, the indentation of a line depends only on the syntax, and cannot be wrong.

There are many similar "problems":

The "wrong operator" problem
Writing "+" when you meant to write "-". This can cause infinite loops and actual errors in code. The solution is never to use the "+" token in your code, only "-". Obviously it would not be possible only to use the "+" token.
The "wrong function" problem
Writing "scanf" when you meant to write "printf". This not only prevents your program from running, it even crashes it! (Well, any half-modern compiler manages to warn your program is completely wrong, but that's besides the point.)
The "dangling semicolon" problem
Writing ";" in the wrong place, e.g.
  printf("i = %d\n",11-i);
prints only a single, wrong, value, instead of 10 correct ones. The solution is to use BASIC, which doesn't use semicolons. Or assembler or LISP, which tend to treat them as comments.

Log in or register to write something here or to contact authors.