如果我尝试编译
for(;;)
{
}
System.out.println("End");
Java 编译器产生错误提示 Unreachable statement
。但是,如果我添加另一个“unreachable”(根据我)break
语句并使它:
for(;;)
{
if(false) break;
}
System.out.println("End");
它编译。为什么它不会产生错误?
最佳答案
行为在 the JLS description of unreachable statements 中定义:
The then-statement is reachable iff the if-then statement is reachable.
因此编译器确定 then 语句 (break;
) 是可达的,而不管 if
中的条件如何。
还有一点,强调我的:
A basic
for
statement can complete normally iff at least one of the following is true:
- The for statement is reachable, there is a condition expression, and the condition expression is not a constant expression (§15.28) with value true.
- There is a reachable
break
statement that exits the for statement.
所以 for 可以正常完成,因为 then 语句包含 break
。如您所见,如果您将 break
替换为 return
,它将不起作用。
基本原理在本节末尾进行了解释。实质上,if
有一种特殊的处理方式,允许以下结构:
if(DEBUG) { ... }
其中 DEBUG 可能是编译时间常数。
关于java - 为什么 Java 编译器不会为无法访问的 then 语句生成无法访问的语句错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34453585/