Code below fails to compile since x=3
is unreachable
while (false) { x=3; }
But why for( int i = 0; i< 0; i++) {x = 3;}
compiles fine? In this code x=3
is also unreachable.
See JLS 14.21, Unreachable Statements.
The contained statement [in a while loop] is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.
false
is a constant expression whose value is false
, so x=3;
is unreachable.
The contained statement [in a basic for loop] is reachable iff the for statement is reachable and the condition expression is not a constant expression whose value is false.
i<0
isn't a constant expression, so the contained statement is considered reachable, even if it is not actually reachable.
The while statement can be proven unreachable in compilation time, whereas the for statement needs to be checked in running time to find it unreachable.
If you try this
int i = 0;
while(i>1) { i = 4; }
The code will compile just fine.