为什么当 if 条件为常量时未检测到无法访问的代码?
Why isn't unreachable code detected when an if condition is a constant?
我正在准备 Java 考试,遇到了 "unreachable statement" 编译器错误,例如:
Source.java:10: error: unreachable statement
System.out.println("This code is not reachable");
我正在尝试了解何时会或不会发生这种情况 - 例如它不会发生在这些情况下:
// 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
}
编译器似乎不够智能,无法检测 if
条件何时持续 true
- 有人可以提供更详细的解释吗?
来自Java语言规范,14.21. Unreachable Statements(我强调):
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.
所以虽然代码确实是不可访问的,但编译器明确地不认为它是不可访问的。声明的原因是允许程序员定义 "flag" 变量,例如
static final boolean DEBUG = false;
if (DEBUG) { x=3; }
应该可以在 false
和 true
之间切换 DEBUG
而无需更改代码中的任何其他内容(由于编译错误)。
我正在准备 Java 考试,遇到了 "unreachable statement" 编译器错误,例如:
Source.java:10: error: unreachable statement
System.out.println("This code is not reachable");
我正在尝试了解何时会或不会发生这种情况 - 例如它不会发生在这些情况下:
// 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
}
编译器似乎不够智能,无法检测 if
条件何时持续 true
- 有人可以提供更详细的解释吗?
来自Java语言规范,14.21. Unreachable Statements(我强调):
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
, andfor
statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.
所以虽然代码确实是不可访问的,但编译器明确地不认为它是不可访问的。声明的原因是允许程序员定义 "flag" 变量,例如
static final boolean DEBUG = false;
if (DEBUG) { x=3; }
应该可以在 false
和 true
之间切换 DEBUG
而无需更改代码中的任何其他内容(由于编译错误)。