Dangling else

from Wikipedia, the free encyclopedia

The problem of dangling else ( English dangling dangling ') is an example of an apparent ambiguity of a programming language, which can cause confusion, especially if a indentation. In fact, the semantics are clearly defined in most languages, if only because the grammar of the language would otherwise not be clearly separable. The problem arises in some programming languages (such as C , C ++ , Java ) when two nested if statements are only faced by an else branch. It can only occur if an optional parenthesis is omitted.

Example (in C )

  if (a == 1)
    if (b == 1)
      a = 42;
  else
    b = 42;

In this example, some users expect the value to be assigned for the case of the variable . However, the compiler refers the else branch to the last if query. In this case the program will not carry out any assignment. If, on the other hand, the value is actually to be assigned in the case , the outer if statement must be bracketed:

  if (a == 1)
  {
    if(b == 1)
      a = 42;
  }
  else
    b = 42;

Other programming languages

In some languages, the problem is circumvented by each if a "closing parenthesis" are assigned must . For example, in the Bourne Shell scripting language , fi stands for the closing bracket. The above algorithm is then as follows:

if [ $a -eq 1 ] ; then
  if [ $b -eq 1 ] ; then
    a=42
  fi
else
  b=42
fi

In other programming languages ​​(e.g. Python ), the problem is avoided by structuring with indentation.

if a == 1:
    if b == 1:
        a = 42
else:
    b = 42

This problem does not occur in Ada due to the unambiguous syntactic bracketing. Each IF is concluded by ENDIF:

IF a = 1 THEN
    IF b = 1 THEN
        a := 42;
    END IF;
ELSE
     b := 42;
END IF;

In Basic, too, each IF is either terminated with END IF (as in Ada) or, in the case of a single statement, this is specified after THEN (without line break):

IF a = 1 THEN
    IF b = 1 THEN a = 42
ELSE
     b = 42
END IF

See also

literature