Dangling else

The problem of dangling else ( engl. = 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 in most languages ​​is clearly defined, if only because the grammar of the language would not be clearly separable otherwise. The problem arises in some programming languages ​​( such as C, C , Java), if two nested if statements opposed to just an else branch. It can occur only when an optional brackets will be omitted.

Example ( C )

If ( a == 1)      if ( b == 1)        a = 42;    else      b = 42; In this example, expect some user that is assigned the value for the case of the variable. The compiler applies the else branch but at the last if statement. The program will run in the case assignment. If on the other hand are actually assigned to the case, the value, the outer if statement must be stapled:

If ( a == 1)    {      if ( b == 1)        a = 42;    }    else      b = 42; Other programming languages

In some languages, the problem is circumvented by must be assigned if a " closing bracket " each. In the Bourne shell scripting language is, for example, fi for the closing parenthesis. 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 ​​(eg Python) to handle the problem by structured by engaging.

If a == 1:      if b == 1:          a = 42 else:      b = 42 In Ada, this problem does not occur by a unique syntactic bracketing. Each IF is terminated by ENDIF:

IF a = 1 THEN      IF b = 1 THEN          a: = 42;      END IF; ELSE       b: = 42; END IF; Also in Basic each IF is completed either by END IF (as in Ada ) or a single statement specified after this THEN ( without line break ):

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

  • Look Ahead
  • Programming
  • Compiler
214485
de