Look at the following infinite while loop in Java. It causes a compile-time error for the statement below it.
while(true) {
System.out.println("inside while");
}
System.out.println("while terminated"); //Unreachable statement - compiler-error.
The following same infinite while loop, however works fine and doesn't issue any errors in which I just replaced the condition with a boolean variable.
boolean b=true;
while(b) {
System.out.println("inside while");
}
System.out.println("while terminated"); //No error here.
In the second case also, the statement after the loop is obviously unreachable because the boolean variable b is true still the compiler doesn't complain at all. Why?
Edit : The following version of while gets stuck into an infinite loop as obvious but issues no compiler errors for the statement below it even though the if condition within the loop is always false and consequently, the loop can never return and can be determined by the compiler at the compile-time itself.
while(true) {
if(false) {
break;
}
System.out.println("inside while");
}
System.out.println("while terminated"); //No error here.
while(true) {
if(false) { //if true then also
return; //Replacing return with break fixes the following error.
}
System.out.println("inside while");
}
System.out.println("while terminated"); //Compiler-error - unreachable statement.
while(true) {
if(true) {
System.out.println("inside if");
return;
}
System.out.println("inside while"); //No error here.
}
System.out.println("while terminated"); //Compiler-error - unreachable statement.
Edit : Same thing with if and while.
if(false) {
System.out.println("inside if"); //No error here.
}
while(false) {
System.out.println("inside while");
// Compiler's complain - unreachable statement.
}
while(true) {
if(true) {
System.out.println("inside if");
break;
}
System.out.println("inside while"); //No error here.
}
The following version of while also gets stuck into an infinite loop.
while(true) {
try {
System.out.println("inside while");
return; //Replacing return with break makes no difference here.
} finally {
continue;
}
}
This is because the finally block is always executed even though the return statement encounters before it within the try block itself.
-
46Who cares? It's obviously just a feature of the compiler. Don't concern yourself with this sort of stuff.CJ7– CJ72011年12月20日 06:00:48 +00:00Commented Dec 20, 2011 at 6:00
-
17How could another thread change a local non-static variable?CJ7– CJ72011年12月20日 06:52:48 +00:00Commented Dec 20, 2011 at 6:52
-
4The internal state of the object might be changed concurrently through reflection. That's why the JLS mandates that only final (constant) expressions be checked.lsoliveira– lsoliveira2011年12月20日 15:11:04 +00:00Commented Dec 20, 2011 at 15:11
-
6I hate these stupid errors. Unreachable code should be a warning not an error.user606723– user6067232011年12月20日 17:35:14 +00:00Commented Dec 20, 2011 at 17:35
-
2@CJ7: I would not call this a "feature", and it makes it very tedious (for no reason) to implement a conforming Java compiler. Enjoy your by-design vendor lock-in.L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳– L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳2013年03月28日 23:32:23 +00:00Commented Mar 28, 2013 at 23:32
16 Answers 16
The compiler can easily and unequivocally prove that the first expression always results in an infinite loop, but it's not as easy for the second. In your toy example it's simple, but what if:
- the variable's contents were read from a file?
- the variable wasn't local and could be modified by another thread?
- the variable relied on some user input?
The compiler is clearly not checking for your simpler case because it's forgoing that road altogether. Why? Because it's (削除) much harder (削除ここまで) forbidden by the spec. See section 14.21:
(By the way, my compiler does complain when the variable is declared final.)
4 Comments
According the specifications, the following is said about while statements.
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 with value true.
- There is a reachable break statement that exits the while statement.\
So, the compiler will only say that the code following a while statement is unreachable if the while condition is a constant with a true value, or there is a break statement within the while. In the second case, since the value of b is not a constant, it doesn't consider the code following it to be unreachable. There's a whole lot more information behind that link to give you more details on just what is and what isn't considered unreachable.
1 Comment
Because true is constant and b can be changed in the loop.
2 Comments
Because analyzing variable state is hard, so the compiler has pretty much just given up and let you do what you wish. Additionally, the Java Language Specification has clear rules about how the compiler is allowed to detect unreachable code.
There are many ways to trick the compiler - another common example is
public void test()
{
return;
System.out.println("Hello");
}
which wouldn't work, as the compiler would realize that the area was unreacable. Instead, you could do
public void test()
{
if (2 > 1) return;
System.out.println("Hello");
}
This would work since the compiler is unable to realize that the expression will never be false.
6 Comments
if is a little different from a while, because the compiler will compile even the sequence if(true) return; System.out.println("Hello"); without complaining. IIRC, this is a special exception in the JLS. The compiler would be able to detect the unreachable code after the if as easy as with while.The latter is not unreachable. The boolean b still has the possibility of being altered to false somewhere inside the loop causing an ending condition.
1 Comment
My guess is the variable "b" has possibility to change its value, so compiler think System.out.println("while terminated");
can be reached.
Comments
Compilers aren't perfect - nor should they be
The responsibility of the compiler is to confirm syntax - not to confirm execution. Compilers can ultimately catch and prevent many run time problems in a strongly typed language - but they cannot catch all such errors.
The practical solution is to have batteries of unit tests to complement your compilers checks OR use object oriented components for implementing logic that are known to be robust, rather then relying on primitive variables and stop conditions.
Strong Typing and OO : increasing compiler's efficacy
Some errors are syntactical in nature - and in Java, the strong typing makes a lot of run time exceptions catchable. But, by using better types, you can help your compiler to enforce better logic.
If you want the compiler to enforce logic more effectively, in Java, the solution is to build robust, required objects that can enforce such logic, and using those objects to build up your application, rather than primitives.
A classic example of this is the use of the iterator pattern, combined with Java's foreach loop this construct is less vulnerable to the type of bug you illustrate than a simplistic while loop.
1 Comment
The compiler is not sophisticated enough to run through the values that b may contain (though you only assign it once). The first example is easy for the compiler to see it will be an infinite loop because the condition is not variable.
1 Comment
I'm surprised your compiler refused to compile the first case. That seems strange to me.
But the second case isn't optimized to the first case because (a) another thread might update the value of b (b) the called function might modify the value of b as a side effect.
Actually I don't think anyone got it QUITE right (at least not in the original questioner's sense). The OQ keeps mentioning:
Correct, but irrelevant, as b is NOT being changed in the loop
But it doesn't matter because the last line IS reachable. If you took that code, compiled it into a class file and handed the class file to someone else (say as a library), they could link the compiled class with code that modifies "b" through reflection, exiting the loop and causing the last line to execute.
This is true of any variable that isn't a constant (or final which compiles to a constant in the location where it's used--sometimes causing bizarre errors if you recompile the class with the final and not a class that references it, the referencing class will still hold the old value without any errors whatsoever)
I've used the ability of reflection to modify non-final private variables of another class to monkey-patch a class in a purchased library--fixing a bug so we could continue developing while we waited for official patches from the vendor.
By the way, this may not actually work these days--although I've done it before, there is a chance that such a small loop will be cached in the CPU cache and since the variable is not marked volatile the cached code may never pick up the new value. I've never seen this in action but I believe it's theoretically true.
2 Comments
b is a method variable. Can you really modify a method variable using reflection? Regardless the overall point is that we should not assume that the last line is not reachable.It is simply because the compiler doesn't to too much baby sitting work, though it is possible.
The example shown is simple and reasonable for compiler to detect the infinite loop. But how about we insert 1000 lines of code without any relationship with variable b? And how about those statements are all b = true;? The compiler definitely can evaluate the result and tell you it is true eventually in while loop, but how slow it will be to compile a real project?
PS, lint tool definitely should do it for you.
Comments
From the compiler's perspective the b in while(b) could change to false somewhere. The compiler just doesn't bother checking.
For fun try while(1 < 2), for(int i = 0; i < 1; i--) etc.
Comments
Expressions are evaluated at run time so, when replacing the scalar value "true" with something like a boolean variable, you changed a scalar value into a boolean expression and thus, the compiler has no way to know it at compilation time.
Comments
If the compiler can conclusively determine that the boolean will evaluate to true at run-time, it will throw that error. The compiler assumes that the variable you declared can be changed (albeit we know here as humans it will not).
To emphasize this fact, if variables are declared as final in Java, most compilers will throw the same error as if you substituted for the value. This is because the variable is defined at compile time (and cannot be changed at run-time) and the compiler can therefore conclusively determine that the expression evaluates to true at run-time.
Comments
The first Statement always result in an infinite loop because we have specify a constant in condition of while loop, where as in second case compiler assume that, there is possibility of change of value of b inside loop.
Comments
• The compiler only issues errors when it detects logically unreachable instructions during compilation.
Cases where values change during runtime are not considered an error during compilation.
To avoid errors:
Add methods to terminate infinite loops (break, return).
Avoid unreachable instructions (such as while(false)).
Be careful with the finally block to avoid unexpected behavior.
Infinite loops with fixed conditions (
trueorfalse):
- If the condition is always
true, the loop must contain an instruction to terminate it (breakorreturn); otherwise, the compiler considers the instructions after the loop to be inaccessible (a compile error). - If the condition is
false, the compiler knows that the loop will never execute, and will issue an error due to the inaccessible instructions inside the loop.
- Using variables as a loop condition:
- If a variable is used as a condition, the compiler does not issue an error because it assumes that the value of the variable may change during execution (Runtime).
- Control instructions inside loops:
breakterminates the loop, making the following instructions accessible.returnexits the function entirely, making the instructions after the loop inaccessible.
- Finally` block:
- Code inside
finallyis always executed, even if there are instructions likereturnorbreakin thetryblock. Usingcontinueinfinallymay result in an infinite loop.
- Error Handling:
- Always ensure that loops can be terminated with logical conditions.
- Avoid instructions that are logically unreachable, such as
while(false).
Write the conditions carefully, and always test that loops terminate as expected to avoid errors during compilation or runtime.