What does "for(;;)" mean?
In C/C++, what do开发者_如何学Ces the following mean?
for(;;){
...
}
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).
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.
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.
An infinite loop which continues until there is a break
, exit
, or goto
statement.
Even if this answer suggests that both constructs are equivalent, there's a subtle difference between both for(;;)
and while(1)
(which both create infinite loops) in the C language (and possibly compiler-dependent).
Some compilers (Windriver DIABData for instance) complain about "condition is always true" when using while(1)
.
Changing to for(;;)
allows to get rid of the warning, probably because the latter expression is semantically stronger to create an infinite loop on purpose, and there is no "always true" condition at all (plus it's shorter to write).
On the other hand, the C++ language doesn't make a difference about both constructs as Adrian stated in comments:
The C++ standard states that a missing condition makes the implied while
clause equivalent to while(true)
and for ( for-init-statement condition opt ; expression opt )
statement is equivalent to { for-init-statement while ( condition ) { statement expression ; } }
精彩评论