Hot Posts

Loops that cause unreachable code errors

The last loop does not compile because of “unreachable code”. The line System.out.println(y); can never be executed because the test condition is always false.

             for (int y=0; false ;y++){
                  System.out.println(y);
            }
            while (false) { x=3; }
            for( int i = 0; false; i++) x = 3;

NOTE THIS EXCEPTION:

     if(false){ x=3; } 

This code does not cause an unreachable code error.

In the following code snippet

     if(false){ x=3; }

, although the body of the condition is unreachable, this is not an error because the JLS explicitly defines this as an exception to the rule. It allows this construct to support optimizations through the conditional compilation. For example,

     if(DEBUG){ System.out.println("beginning task 1"); }

Here, the DEBUG variable can be set to false in the code while generating the production version of the class file, which will allow the compiler to optimize the code by removing the whole if statement entirely from the class file.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: