Why Java identifies unreachable code only in case

2019-01-28 05:44发布

This question already has an answer here:

If I have code like

public static void main(String args[]){
    int x = 0;
    while (false) { x=3; }  //will not compile  
}

compiler will complaint that x=3 is unreachable code but if I have code like

public static void main(String args[]){
    int x = 0;
    if (false) { x=3; }
    for( int i = 0; i< 0; i++) x = 3;   
}

then it compiles correctly though the code inside if statement and for loop is unreachable. Why is this redundancy not detected by java workflow logic ? Any usecase?

4条回答
可以哭但决不认输i
2楼-- · 2019-01-28 06:19

The use case with the if condition is debugging. AFAIK it is explicitly allowed by the spec for if-statements (not for loops) to allow code like this:

class A {
    final boolean debug = false;

    void foo() {
        if (debug) {
            System.out.println("bar!");
        }
        ...
    }
}

You can later (or via debugger at runtime) change the value of debug to get output.

EDIT As Christian pointed out in his comment, an answer linking to the spec can be found here.

查看更多
时光不老,我们不散
3楼-- · 2019-01-28 06:28

As described in Java Language Specification, this feature is reserved for "conditional compilation".

An example, described in the JLS, is that you may have a constant

static final boolean DEBUG = false;

and the code that uses this constant

if (DEBUG) { x=3; }

The idea is to provide a possibility to change DEBUG from true to false easily without making any other changes to the code, which would not be possible if the above code gave a compilation error.

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-28 06:28

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.

查看更多
三岁会撩人
5楼-- · 2019-01-28 06:31

Regarding the for loop, I thinks it's just that it's not as easy to detect as the use of a false constant inside a while loop.

Regarding the if, that was a deliberate choice to authorize it in order to be able to remove debugging code from the byte code at compilation time:

private static final boolean DEBUG = false; // or true

...

if (DEBUG) {
    ...
}
查看更多
登录 后发表回答