0

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.

vico
  • 17,051
  • 45
  • 159
  • 315

2 Answers2

2

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

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.

Ssr1369
  • 348
  • 3
  • 16