Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't unreachable code detected when an if condition is a constant?

I'm studying for a Java exam and came across the "unreachable statement" compiler error, e.g:

Source.java:10: error: unreachable statement
       System.out.println("This code is not reachable");

Am trying to understand when this would or wouldn't happen - e.g. it doesn't happen for these cases:

// Case #1
if (true) {
    System.out.println("This code is reachable");
} else {
    System.out.println("This code is not reachable"); // Compiles OK
}

// Case #2
for (i = 0; i < 5; i++) {
    if (true) continue;
    System.out.println("This code is not reachable"); // Compiles OK
}

It seems the compiler isn't smart enough to detect when the if condition is constantly true - could someone provide a more detailed explanation?

like image 839
Steve Chambers Avatar asked Jan 12 '20 15:01

Steve Chambers


Video Answer


1 Answers

From the Java Language Specification, 14.21. Unreachable Statements (emphasis by me):

It is a compile-time error if a statement cannot be executed because it is unreachable.

This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer, or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.

So while the code is indeed unreachable, the compiler explicitly does not regard it as such. The reason stated is to allow programmers to define "flag" variables such as

static final boolean DEBUG = false;

if (DEBUG) { x=3; }

It should be possible to switch DEBUG between false and true without having to change anything else in the code (due to compilation errors).

like image 109
Marvin Avatar answered Oct 19 '22 17:10

Marvin