Why is an if/else if/else for a simple boolean not giving an “unreachable code” error

别等时光非礼了梦想. 提交于 2019-11-29 10:31:37

问题


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;
    }
}

回答1:


From JLS 14.21. Unreachable Statements

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

and

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

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 */ }

This is not true for while

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

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

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



来源:https://stackoverflow.com/questions/36086502/why-is-an-if-else-if-else-for-a-simple-boolean-not-giving-an-unreachable-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!