-2

Got a practice question, and I have the below code:

while (false) { x=3; }

The x=3 is unreachable code, and I don't really understand why. There is a similar section of code:

if (false) { x=3; }

which is perfectly valid.

May be a bit of a noob question, or may be I'm just missing something, but if you could help me understand why that'd be great, thanks!

I am asking specifically about the difference between the if and while statement, because the same line of code changed to if, is valid and will compile.

Sam
  • 223
  • 3
  • 7
  • Code is unreachable means the compiler deemed it that there cannot be no path to statement `x=3;` because `while ( false )`can never be `true` – SomeDude Aug 09 '16 at 11:32
  • The kicker is: neither can `if(false)`. The real question is: why does the compiler not have problems with the if statement. – Gimby Aug 09 '16 at 11:34
  • 1
    And for the second part of the question, refer to http://stackoverflow.com/a/8570302/1743880 – Tunaki Aug 09 '16 at 11:34
  • 1
    And refer to http://stackoverflow.com/questions/20299914/iffalse-vs-whilefalse-unreachable-code-vs-dead-code also – Tunaki Aug 09 '16 at 11:35
  • This is NOT a duplicate, the other question is asking about if and not while statements! – Sam Aug 09 '16 at 11:36
  • 1
    Please refer to the above questions also. They explain this behaviour both for if and while statements, by referencing the Java specification. See http://stackoverflow.com/questions/20299914/iffalse-vs-whilefalse-unreachable-code-vs-dead-code – Tunaki Aug 09 '16 at 11:37
  • It is a duplicate of this too which specifically mentions while loops. Whether it's an if or a loop, the answer is still the same. http://stackoverflow.com/questions/9302133/why-is-this-code-giving-an-unreachable-statement-error – Lexi Aug 09 '16 at 11:53
  • Ok, well I had a look for questions previously asked and didn't find those, thanks for linking them – Sam Aug 09 '16 at 11:55
  • So essentially because it never starts as false to then become true, but it is actually true and then becomes false, the while loop will never execute, hence the unreachable code? – Sam Aug 09 '16 at 11:56

1 Answers1

1

Read below article it will answer your question: http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21

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

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

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

The contained statement is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.

erni
  • 45
  • 1
  • 10