java - (编译器) else if(true) vs else 场景

标签 java if-statement compiler-construction language-lawyer

获取以下 Java 代码片段:

....
    else if (true){ //hard-coded as true
     ///launch methodA
    }
    else {
     ///launch methodA (same code as in the ` else if ` statement)
    }
....

我想知道的是编译器如何处理这个问题。编译器完全删除 else if(true) 语句以便不必执行检查是否合乎逻辑,即使它被硬编码为真。特别是在 Eclipse 中,上面的代码是如何解释的?

或者在下面的场景中呢:

....
    else if (true){ //hard-coded as true
     ///launch methodA
    }
    else {
     ///launch methodBB
    }
....

在这种情况下编译器删除 else 语句不是合乎逻辑吗?因为在运行时,else 语句是无法访问的。

最佳答案

无法访问的语句在 Java 中是被禁止的,并且必须触发编译错误。 JLS 定义了什么是不可访问的语句: https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21

这里引用太长了,但这里是摘录(强调我的):

if (false) { x=3; }

does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false;

and then write code such as:

if (DEBUG) { x=3; }

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

所以答案将取决于您使用的编译器及其优化选项。

关于java - (编译器) else if(true) vs else 场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32503355/

相关文章:

java - JPA EntityManager.getSingleResult() 为 COUNT 查询返回什么?

java - 如何获取片段着色器的坐标? gl_FragCoord 不工作

c - 写入文件并使用带循环的 if 语句

c++ - 代码格式化会导致目标文件内容发生变化吗?

java - 带有 java.util.Calendar 的非标准语言环境

java - ResultSet 方法 previous() 不起作用

java - 校验值为 'ceiling' 值并返回对应变量

bash - 我怎样才能在 bash 中找到 "try to do something and then detect if it fails"?

compiler-construction - 使用 F# 的 Staticlink 与独立怪癖

android - 如何只编译使用过的资源