java - 为什么 Java 编译器不会为无法访问的 then 语句生成无法访问的语句错误?

标签 java if-statement unreachable-code unreachable-statement

如果我尝试编译

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/

相关文章:

java - 在java中设置数据库文件的路径

java - 优先级队列比较——Java 与 C++

java - 在 if 中放置一个返回 boolean 值的方法在功能上等同于直接调用该方法吗?

c# - 避免过多的 if else, else if 语句用于多个 (9) 条件

exception - 捕获 block 避免编译错误?

java - iceWm 窗口管理器窗口问题

java - Swing Action 执行方法

if-statement - 如何在结构初始化中添加if语句

java - 为什么不是遥不可及呢?

java - if(false) 与 while(false) : unreachable code vs. 死代码