Why does a Java Compiler not produce an unreachable statement error for an unreachable then statement?

后端 未结 5 986
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 17:33

If I try to compile

for(;;)
{

}
System.out.println(\"End\");

The Java compiler produces an error saying Unreachable statement

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 18:33

    From the JLS

    An if-then statement can complete normally if at least one of the following is true:

    > The if-then statement is reachable and the condition expression is not a constant expression whose value is true.

    > The then-statement can complete normally.

    So if(false) is allowed.

    This ability to "conditionally compile" has a significant impact on, and relationship to, binary compatibility. If a set of classes that use such a "flag" variable are compiled and conditional code is omitted, it does not suffice later to distribute just a new version of the class or interface that contains the definition of the flag. A change to the value of a flag is, therefore, not binary compatible with pre-existing binaries . (There are other reasons for such incompatibility as well, such as the use of constants in case labels in switch statements;)

提交回复
热议问题