为什么简单布尔值的 if/else if/else 没有给出“无法访问的代码"?错误

2022-01-19 00:00:00 boolean java unreachable-code

为什么这段代码没有给出无法访问的代码"错误?因为布尔值只能是真或假.

Why is this code not giving an "unreachable code" error? Since a boolean can only be true or false.

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.无法访问的语句

如果由于无法访问而无法执行语句,则为编译时错误.

It is a compile-time error if a statement cannot be executed because it is unreachable.

如果 if-then-else 语句可达,则 else 语句可达.

The else-statement is reachable iff the if-then-else statement is reachable.

您的 if-then-else 语句是可访问的.因此,根据定义,编译器认为 else 语句是可访问的.

Your if-then-else statement is reachable. So, by the definition the compiler thinks that the else-statement is reachable.

注意:有趣的是,下面的代码也可以编译

Note: Interestingly the following code also compiles

// This is ok
if (false) { /* do something */ }

这不适用于 while

// This will not compile
while (false) { /* do something */ }

因为 while 的可达性定义不同(强调我的):

because the reachability definition for while is different (emphasis mine):

如果while语句可达且条件表达式不是值为false的常量表达式,则包含的语句是可达的.

The contained statement is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.

相关文章