(编译器)否则if(true)vs else scenario [英] (Compiler) else if(true) vs else scenario

查看:261
本文介绍了(编译器)否则if(true)vs else scenario的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取以下Java代码段:

Take the following Java code snippet:

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

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

What I was wondering is how the compiler deals with this. Wouldn't it be logical for the compiler to remove the else if(true) statement altogether in order to not have to perform a check, even though it is hard-coded as true. Specifically in Eclipse, how is the code above interpreted?

或者在以下情况中如何:

Or what about in the following scenario:

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

在这种情况下,对于编译器删除 else 语句?因为在运行时, else 语句无法访问。

Wouldn't it be logical in this case for the compiler to remove the else statement? Because while running, the else statement is unreachable.

推荐答案

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

Unreachable statements are forbidden in Java and must trigger compilation errors. The JLS defines what is an unreachable statements: https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21

它也是这里有一个摘录(强调我的):

It is too long to be entirely quoted here, but here is an extract (emphasis mine):


if (false) { x=3; }

不会导致编译时错误。优化编译器可能
意识到语句x = 3;将永远不会执行,可能选择
从生成的类文件中省略该语句的代码,但
语句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;

然后编写如下代码:

if (DEBUG) { x=3; }

这个想法是应该可以将DEBUG的值从false更改为true或者从如果为true,则为true,然后正确编译代码,而不对程序文本进行其他更改。

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.

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

So the answer will depend on the compiler you use and its optimization options.

这篇关于(编译器)否则if(true)vs else scenario的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆