• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

unreachable code-K&B p343

 
prajal Mehta
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The following code doesn't compile saying the code is unreachable-


But following code (from K and B , page 343) does compile, even though the line - ' System.out.println("outer");' is never going to print , then why doesn't compiler treats it as unrechable code? :roll:


I am confused.
Please somebody give me tips on how to determine if a given line of code is unreachable and when will the program fail to compile?

I am planning to give my scjp exam on thursday!
[ January 07, 2008: Message edited by: prajal Mehta ]
 
srinivas sridaragaddi
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi prajal,

Some situations where in unreachable statement error is thrown are statements after continue,break,return,if the condition is set to false etc....

their are some other cases. In your example when control reaches continue control has to be moved to label outer and hence for any value of i,j the
statement System.out.println("Outer"); is not executed hence unreachable statement error is thrown.

consider this

while(false)
{
System.out.println("hello");//unreachable statement
}

in this case also compiler knows that the condition is always false hence the statement inside the loop is never going to execute and hence unreachble statement.


where are the same is not true in this case

i=2;
j=3;
while(i>j)
{
System.out.println("hello");//compiles fine
}

even though the condition is false for the given value, compiler thinks that values of i and j can be changed or chances of condition becoming true exists and hence no error.

Hope this helps
[ January 07, 2008: Message edited by: srinivas sridaragaddi ]
 
Raman Gopalan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I agree with sreenivas..correct me if i am wrong
This is from the specification : Pg 402
"...the values of expressions are not taken into account in the flow analysis"

In this case,
outer:
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
System.out.println("Hello");
continue outer;
} // end of inner loop
System.out.println("outer"); // Never prints --but why

the inner loop's condition expression ( j <5) can be replaced by j <0 and thus, System.out.println("outer") can be made reachable .
 
Thirumalai Muthu
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent explanation srinivas and raman
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic