为什么简单布尔值的 if/else if/else 不给出 "unreachable code" 错误
Why is an if/else if/else for a simple boolean not giving an "unreachable code" error
为什么这段代码没有给出 "unreachable code" 错误?由于布尔值只能为真或假。
public static void main(String args[]) {
boolean a = false;
if (a == true) {
} else if (a == false) {
} else {
int c = 0;
c = c + 1;
}
}
来自JLS 14.21. Unreachable Statements
It is a compile-time error if a statement cannot be executed because it is unreachable.
和
The else-statement is reachable iff the if-then-else statement is reachable.
您的 if-then-else 语句可以访问。因此,根据定义,编译器认为 else 语句是可达的。
注意:有趣的是,下面的代码也可以编译
// This is ok
if (false) { /* do something */ }
这不适用于 while
// This will not compile
while (false) { /* do something */ }
因为 while
的可达性定义不同(强调我的):
The contained statement is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.
为什么这段代码没有给出 "unreachable code" 错误?由于布尔值只能为真或假。
public static void main(String args[]) {
boolean a = false;
if (a == true) {
} else if (a == false) {
} else {
int c = 0;
c = c + 1;
}
}
来自JLS 14.21. Unreachable Statements
It is a compile-time error if a statement cannot be executed because it is unreachable.
和
The else-statement is reachable iff the if-then-else statement is reachable.
您的 if-then-else 语句可以访问。因此,根据定义,编译器认为 else 语句是可达的。
注意:有趣的是,下面的代码也可以编译
// This is ok
if (false) { /* do something */ }
这不适用于 while
// This will not compile
while (false) { /* do something */ }
因为 while
的可达性定义不同(强调我的):
The contained statement is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.