为什么简单布尔值的 if/else if/else 没有给出“无法访问的代码"?错误 [英] Why is an if/else if/else for a simple boolean not giving an "unreachable code" error

查看:29
本文介绍了为什么简单布尔值的 if/else if/else 没有给出“无法访问的代码"?错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于为什么简单布尔值的 if/else if/else 没有给出“无法访问的代码"?错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆