unreachable statement in java??

Oct 07, 2009 14:49

As far as I know Javac or any other compiler never try to find program is in infinite loop or not. because one can not write a program to find a program is in infinite loop with complete accuracy.

Then how they identify unreachable statement? see the code below... both the code are in infinite loop

class foo
{
      public static void main(String[] ( Read more... )

busy coding...

Leave a comment

Comments 7

rkvsraman October 7 2009, 10:09:37 UTC
Pretty simple.

It is very easy for compiler to detect that while(true) is an infinite loop and so it has to be supplemented by a break in the block for it to exit. But it is very difficult for compiler to predict that the value of j will not change at any point of time and so it does not give ant error.

Reply

pinch_hitter October 7 2009, 10:49:21 UTC
Means you are saying compile do check for infinite loop ?

Reply

rkvsraman October 7 2009, 10:50:39 UTC
Yes, at a basic level.

Reply

pinch_hitter October 9 2009, 12:10:44 UTC
what about the below code ?
class Test{
static void foo(){
while(true){
if(false)
break;
}
return;
}

public static void main(String[] args){
foo();
}
}

Reply


dangiankit October 7 2009, 10:30:07 UTC
while(true)
In the first case, at the compilation time, the compiler knows that the loop needs to be executed infinitely as the terminating condition for the while loop is always true.

while(j==0)
In the second case, at the compilation time, the compiler does not know whether the loop will be executed infinitely as the terminating condition is dependent on the value of the variable j.

More details can be obtained from the Java Language Specifications at this URL.

Reply

pinch_hitter October 7 2009, 10:57:40 UTC
what about this?

class foo
{
public static void main(String[] args)
{
boolean f = true;
while(f)
System.out.println("Hello");
return;
}
}

Reply

pinch_hitter October 7 2009, 11:01:46 UTC
Sorry ! I had not read the link before posting the reply..
"The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis."

Reply


Leave a comment

Up