Unreachable code error vs. dead code warning in Java under Eclipse?

后端 未结 8 1448
眼角桃花
眼角桃花 2020-11-28 06:59

Does anyone know why:

public void foo()
{
    System.out.println(\"Hello\");
    return;
    System.out.println(\"World!\");
}

Would be rep

8条回答
  •  感情败类
    2020-11-28 07:19

    This is to allow a kind of conditionally compilation.
    It is not an error with if, but the compiler will flag an error for while, do-while and for.
    This is OK:

    if (true) return;    // or false
    System.out.println("doing something");
    

    This are errors

    while (true) {
    }
    System.out.println("unreachable");
    
    while (false) {
        System.out.println("unreachable");
    }
    
    do {
    } while (true);
    System.out.println("unreachable");
    
    for(;;) {
    }
    System.out.println("unreachable");
    

    It is explained at the end of JLS 14.21: Unreachable Statements:

    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.

提交回复
热议问题