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

1

6

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?

Saphena answered 12/1, 2020 at 15:55 Comment(1)
The analysis appears to be complete but unsound so it may miss errors but the ones it does give are never false. This is a design choice of the analysis.Atonic
S
6

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).

Sanhedrin answered 12/1, 2020 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.