Java – unreachable statement: while true vs if true

There is already an answer to this question: > unreachable statement error using while loop in Java 2

while (true) return;
System.out.println("I love Java");
// Err: unreachable statement

if (true) return;
System.out.println("I hate Java");
// OK.

thank you.

Edit:

A few minutes later, I found one thing:

In the first case, the compiler throws an error due to an infinite loop In both cases, the compiler does not consider the code results in the statement

Editor 2:

What's your impression of javac now

if (true) return; // Correct
}
    while (true) return; // Correct
}

It looks like javac knows what an inner loop is if the result, but when you write another command (such as the first example), you will get non equivalent behavior (it looks like javac has forgotten what an inner loop / if is)

Public static final edit 3: as a result of this answer, I can say (I hope it is correct): expressions such as (ARG) {...; return;} And while (ARG) {...; return;} Syntactically and syntactically (in bytecode) equivalent to Java IFF argv is a non constant (or valid final type) expression If argv is a constant expression, the bytecode (and behavior) may be different

Abandoning this problem is not an unattainable statement, but a different treatment of logical equivalent expressions, such as true return, if true return

Solution

When statements in Java are reachable, there are very strict rules These rules are easy to evaluate design, not 100% It should prevent basic programming errors To understand accessibility in Java, you are limited to these rules, "common logic" does not apply

So here is the Java language specification @ L_ 404_ 3 @ rules

So nothing else, statements after if then are always accessible

The condition is a constant expression "true" without interruption Therefore, it cannot be completed normally

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>