What does "for(;;)" mean?
In C/C++, what does the following mean?
for(;;){
...
}
It's an infinite loop, equivalent to while(true)
. When no termination condition is provided, the condition defaults to true
.
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.