Search

ParaSoft

HOME
PRODUCTS
SUPPORT
ABOUT
WHAT'S NEW
EVENTS


Jtest

Quick Facts

Technical Papers

Support & Manuals

FAQs

Recent Reviews

User Testimonials

Press Releases

Jtest tool to debug Java(tm)





Contents  Previous  Next  Index

PB.ADE: Avoid dangling "else" statements


DESCRIPTION

This rule flags any dangling "else" statement.

In the following code, it appears that the programmer's intention is to decrement i if i < 5. The compiler always associates an "else" with the previous if unless instructed by braces to do otherwise. In our 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".

EXAMPLE

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

DIAGNOSIS

Avoid dangling "else" statements. Possible confusion: which "if" does the "else" belong to?

REPAIR

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


Contents  Previous  Next  Index

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