• Post Reply Bookmark Topic Watch Topic
  • New Topic

Indefinite loop  RSS feed

 
Chitra AP
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will happen when you attempt to compile and run the following code?

public class Cjgreen{
public static void main(String argv[]){
Cjgreen c = new Cjgreen();
c.jgreen();

}
public void jgreen(){
int iNum =1 ;
while(iNum >0){

toffer:
for(int i = 0; i < 3; i ++){
continue toffer;
System.out.println(i);
}
}

iNum --;
}
}

I think this for loop will cause an indefinite loop and nothing prints.
The answer says Compiler error. How could it be?
 
Ashok Kumar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this for loop will cause an indefinite loop and nothing prints.
The answer says Compiler error. How could it be?


Here the SOP stmt after the for loop becomes unreachable code because of the continue label.So the compiler will generate a Unreachable code error.
 
Ahmed Ossman
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is right!!
It is a compilation error.

The System.out.println() will never be reachable.

It is forbidden as the continue statement will loop for 3 time and goes out
 
Ashok Kumar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is forbidden as the continue statement will loop for 3 time and goes out


The continue stmt will cause an infinite loop and not loop for 3 times,because each time i is initialized to 0.So the for(i<3)condition is always satisfied.
 
Roman Tomach
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ashok Kumar:

The continue stmt will cause an infinite loop and not loop for 3 times,because each time i is initialized to 0.So the for(i<3)condition is always satisfied.

AFAIK, continue statement just breaks current iteration. So, loop variable is incremented.
 
amit taneja
Ranch Hand
Posts: 817
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here continue statment will cause incrementa statment to execute always..

its written in k&B ...that on continue statement the loop starts again but itrator is executed and below statements of continue are skiped and new itration of loop starts...

but my question is that ...NO where is written that unreachable statements will give compiler error ....

i mean ....why it should give complier error...
why it should not allow to run inifinite...

and what if there is not condition in a loop like
while(true) or for(;;

???
show me the link where its written that unreachable statement will cause compiler error....
no logic for such rule..?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!