Jtest logo




Contents  Previous  Next  Index

PB.ADE


Avoid dangling "else" statements

Description

This rule flags any dangling "else" statement.

Example

The developer that wrote the following code intended to decrement i if i <= 5. The compiler always associates an "else" with the previous "if" unless instructed by braces to do otherwise. In this example, the "else" is associated with the second "if"; therefore, the decrementation takes place "if (i >= 2)". To force the structure to execute as originally planned, use braces to indicate to the compiler that the "else" matches the first "if".

 package PB;
 
 public class ADE {
     void method () {
         int i = 5;
         if (i < 5)
             if (i < 2)
                 i++;
         else
             i--;
     }
 }

Repair

Include the first "if" structure between braces. The compiler will know that the second "if" structure is the only statement within the first "if" block and the "else" matches the correct "if".

 void method () {
         int i = 5;
         if (i < 5) {
             if (i < 2)
                 i++;
         } else
             i--;
     }
 }

Contents  Previous  Next  Index

ParaSoft logo
(888) 305-0041 info@parasoft.com Copyright © 1996-2001 ParaSoft