Dangling Else

 [Previous Chapter]  [Previous Page]  [Contents]  [Next Page]  [Next Chapter]

         if (guess != secretNumber)
            if (guess < secretNumber)
               System.out.println("Too small!");
            else
               // guess > secretNumber
               System.out.println("Too large!");

*To which conditional statement does the else branch belong?
 
*Answer: If it can be associated with multiple if statements, the innermost one is taken.
 
*Block statements (i.e. { ... }) can be used to override this.
 
*The coding standard avoids this problem by requiring block statements for the branch that is executed if the condition evaluates to true.
 

 [Previous Chapter]  [Previous Page]  [Contents]  [Next Page]  [Next Chapter]
Copyright © 2001, 2002 Andreas Borchert, converted to HTML on February 11, 2002