Why compiler doesn't generate 'unreachable statement' for 'if (false)'
statement?
The Java compiler won't complain about unreachable code due to an if statement
with a constant expression, such as if (false). The if statement is a special case, because Java's designers
wanted to allow us to use compile-time constant booleans to enable conditional
compilation. Basically, if (false) {...} is allowed, but while
(false) {...} is not.
The if statement, whether or not it has an else part,
is handled in an unusual manner. It is discussed separately at the end of
JLS3 14.21 section:
if (false) { x=3; }
does not result in a compile-time error. An
optimizing compiler may realize that the statement x=3; will never
be executed and may choose to omit the code for that statement from the
generated class file, but the statement x=3;
is not regarded as "unreachable" in the technical sense specified here.
The rationale for this differing treatment is to allow programmers to define
"flag variables" such as:
static final boolean DEBUG = false;
and then write code such as:
if (DEBUG) { x=3; }
The idea is that it should be possible to
change the value of DEBUG from false to true
or from true to false
and then compile the code correctly with no other changes to the program text.