0

The below code gives compile time error - Unreachable statement

while(true)
  return;
return;  // Unreachable statement

But, the following code does not give any error:

if(true)
   return;
return;  // Reachable, No Error

I am unable to understand why the compiler recognizes that in case of while, the 2nd return statement will never be reached, but it does not recognize the same in case of if?

paidedly
  • 1,413
  • 1
  • 13
  • 22
  • 2
    Answer: Java sucks at solving the Halting Problem. :) – Mysticial Jun 08 '15 at 14:30
  • 1
    Here is specification, if someone is willing to dig into it: https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21 . At the end it gives rationale, why it considers `x=3;` reachable in `if(false) x=3;` – zch Jun 08 '15 at 14:33
  • Yeah, the bottom line is that the compiler analysis is limited. There's a specific clause regarding `while (true)` statements, the same does not exist for `if`. – Dave Newton Jun 08 '15 at 14:34
  • The better dupe is the link pointed at in this question's dupe: http://stackoverflow.com/questions/20299914/iffalse-vs-whilefalse-unreachable-code-vs-dead-code – Dave Newton Jun 08 '15 at 14:36

0 Answers0