Why does Java only identify unreachable code in the case of a while loop?

If I have a code like

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

the compiler will complain that x=3is 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;   
}

it compiles correctly, even though the code inside if statementand for loopinaccessible. Why is this redundancy not detected by the Java workflow logic? Any user?

+4
source share
4 answers

As described in the Java Language Specification , this function is reserved for conditional compilation.

An example described in JLS is that you might have a constant

static final boolean DEBUG = false;

,

if (DEBUG) { x=3; }

, DEBUG true false - , , .

+7

if - . AFAIK if -statements ( ), :

class A {
    final boolean debug = false;

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

( ) debug .

, , , .

+2

for, , false while.

if, , :

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

...

if (DEBUG) {
    ...
}
+2

if (false) {x = 3; } . , x = 3; , x = 3; "" , .

, " ", :

static final boolean DEBUG = false; , :

if (DEBUG) {x = 3; } The idea is that it should be possible to change the DEBUG value from false to true or from true to false, and then compile the code correctly without any changes to the program text.

-1
source

Source: https://habr.com/ru/post/1542803/


All Articles