Why does the compiler return invalid code in some cases

If i write

private void check(){ if(true) return; String a = "test"; } 

The above code works fine, but if I write

 private void check(){ return; String a = "test"; } 

The compiler / gradle in Android studio does not skip this, even if it is the same, and it says that the code after returning in example 2 is not available.

I have no problem regarding this, but I really want to know why?

+7
java android android-studio javac
source share
4 answers

This is explained by the Unreachable Statementments part of the Java language specification.

There are quite a few rules with an interesting special case. This is a compile time error:

 while (false) { // this code is unreachable String something = ""; } 

while this is not so:

 if (false) { // this code is considered as reachable String something = ""; } 

This reason is to allow some conditional compilation, for example:

 static final boolean DEBUG = false; ... if (DEBUG) { x=3; } 

So in your case:

 private void check(){ if(true) return; // NO compilation error // this is conditionnal code // and may be omitted by the compiler String a = "test"; } 

is not an error due to special if processing, using while not accepted instead:

 private void check(){ while(true) return; // "Unreachable statement" compilation error String a = "test"; } 

This is also a mistake:

 private void check(){ if(true) return; else return; // "Unreachable statement" compilation error String a = "test"; } 
+1
source share

javac compiler does very few optimizations, so it just does not see that if(true) always true (but you should get a warning); but the C1 / C2 JIT compilers will be - so the code will just be return , without an if statement.

+1
source share

When he tries to compile, he creates an abstract syntax tree. In the first case, "truth" is an anonymous variable, so two branches will be added, even one of them is possible. In the second case, only one possible branch is created, which will never reach the end.

0
source share

The difference is that two different analyzes are required to determine behavior. The first example requires semantic analysis, while later parsing is required. Compilers are experts in syntax; this is what they are made for. However, they often struggle with semantics. Performing static semantic analysis requires more effort from the authors of the compiler and it can be extremely difficult to get the right one as a whole.

0
source share

All Articles