问题
When I'm compiling this code
public static void main(String [] args) {
int x = 0;
while(false)
{
System.out.println(hello);
}
}
it is showing compile time error unreachable code.
But when I modified this code to
public static void main(String [] args) {
int x = 0;
boolean result = false;
while(result)
{
x=4;
}
}
it's working fine.
Can somebody tell me the reason behind this behavior.
回答1:
It is because boolean result = false
is not a constant expression whereas false
is. If you try the code below, it won't compile either because result
is now a constant:
final boolean result = false;
while(result) { x=4; }
However this would compile, because result is not a constant variable any longer:
final boolean result;
result = false;
while(result) { x=4; }
See also: Why does the Java compiler not understand this variable is always initialized? for a similar discussion.
回答2:
Usage of constant false
in the following statement
while(false)
is resolved to false at compilation time hence compiler complains for unreachable code.
But when you use a variable instead:
boolean result = false;
while(result)
compiler is not sure about the value of it at compile time and hence does not complain.
回答3:
The behavior of the compiler is precisely specified in the Java Language Specification, Section 14.21. Unreachable Statements.
Here is a key quote, which directly addresses your question:
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.
回答4:
Java uses a simple flow analysis algorithm to find most common cases of unreachable code, and all such unreachable code blocks will be flagged as compile-time errors. That's why your "while (false) { ... }" statement produces an error.
来源:https://stackoverflow.com/questions/20922371/unreachable-code-while-loop