What is the meaning of for (;;)
?
I found it in a certain base class and I cannot find explanation for in on the net.
Please also explain when and how to use this expression
What is the meaning of for (;;)
?
I found it in a certain base class and I cannot find explanation for in on the net.
Please also explain when and how to use this expression
It's an infinite loop. It has no initial condition, no increment and no end condition.
It's the same as
while(true) {
//do stuff
}
You can use it when you need something to be repeated continuously, until the application ends. But i would use the while
version instead
It is read "for ever". the default for the condition is to evaluate to true.
When should you use it? If you don't want the loop to end (as is common in servers) or when the end condition is naturally known only in the middle of the loop, in which case you can use break
:
for (;;) {
String in = get_input();
if (in.equals("end"))
break;
System.out.println("you entered " + in);
}
This is not the best example, though. You can do without the infinite loop here. For example:
for (String in = get_input(); !in.equals("end"); in = get_input()) {
System.out.println("you entered " + in);
}
It means an infinite loop. It is not considered a good practice to use this. Instead try while(true)
In some cases where you want to do a task again and again, sometimes forever. Such cases you use an infinite loop. This can be done in many ways. Notable ones are,
Using while
,
while(true)
{
// Task you want to repeat
}
Using for
,
for(;;)
{
// Task you want to repeat
}
Note : You might have to be very much careful while implementing infinite loops as there exists a possibility of same problem recurring. It is a good practice to catch the exception and retry for some time and if still problem persist, break from the loop.