What does "for(;;)" mean?
Loop until some break
, exit
, throw
etc. statement inside the loop executes. Basically, you can think of a for
loop as consisting of:
for (setup; test; advance)
...
If the "test" is empty it's considered to be true
, and the loop keeps running. Empty "setup" and "advance" simply do nothing.
It's an infinite loop, equivalent to while(true)
. When no termination condition is provided, the condition defaults to false (i.e., the loop will not terminate).
An infinite loop which continues until there is a break
, exit
, or goto
statement.
In C and C++ (and quite a few other languages as well), the for
loop has three sections:
- a pre-loop section, which executes before the loop starts;
- an iteration condition section which, while true, will execute the body of the loop; and
- a post-iteration section which is executed after each iteration of the loop body.
For example:
for (i = 1, accum = 0; i <= 10; i++)
accum += i;
will add up the numbers from 1 to 10 inclusive.
It's roughly equivalent to the following:
i = 1;
accum = 0;
while (i <= 10) {
accum += i;
i++;
}
However, nothing requires that the sections in a for
statement actually contain anything and, if the iteration condition is missing, it's assumed to be true.
So the for(;;)
loop basically just means:
- don't do any loop setup;
- loop forever (breaks, returns and so forth notwithstanding); and
- don't do any post-iteration processing.
In other words, it's an infinite loop.