Unreachable statement: while true vs if true

marek094 :

How should I understand this Java compiler behaviour?

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

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

Thanks.

EDIT:

I find out the point after a few minutes:

In the first case compiler throws error because of infinite loop. In both cases compiler does not think about the code inside the statement consequent.

EDIT II:

What impress me on javac now is:

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

It looks like javac knows what is inside both loop and if consequent, but when you write another command (as in the first example) you get non-equivalent behaviour (which looks like javac forgot what is inside loop/if).

public static final EDIT III: As the result of this answer I may remark (hopefully correct): Expressions as if (arg) { ...; return;} and while (arg) { ...; return;} are equivalent both semantically and syntactically (in bytecode) for Java iff argv is non-constant (or effectively final type) expression. If argv is constant expression bytecode (and behaviour) may differs.

Disclaimer This question is not on unreachable statements but different handling of logically equivalent expressions such as while true return and if true return.

k5_ :

There are quite strict rules when statements are reachable in java. These rules are design to be easily evaluated and not to be 100% acurate. It should prevent basic programming errors. To reason about reachability in java you are restricted to these rules, "common logic" does not apply.

So here are the rules from the Java Language Specification 14.21. Unreachable Statements

An if-then statement can complete normally iff it is reachable.

So without an else, statements after an if-then are always reachable

A while statement can complete normally iff at least one of the following is true:

  • The while statement is reachable and the condition expression is not a constant expression (§15.28) with value true.

  • There is a reachable break statement that exits the while statement.

The condition is a constant expression "true", there is no break. Hence it does not complete normally.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=455613&siteId=1