| Labels | ||||
| Expression statements | ||||
| Compound statements | ||||
| Selection statements | ||||
| Iteration statements | ||||
for | ||||
| Jump statements | ||||
Executes a loop.
Used as a shorter equivalent ofwhile loop.
Contents |
attr-spec-seq(since C23)(optional)for(init-clause;cond-expression;iteration-expression)loop-statement | |||||||||
Behaves as follows:
| (since C99) |
init-clause,cond-expression, anditeration-expression are all optional. Ifcond-expression is omitted, it is replaced with a non-zero integer constant, which makes the loop endless:
for(;;){printf("endless loop!");}
loop-statement is not optional, but it may be a null statement:
for(int n=0; n<10;++n,printf("%d\n", n));// null statement
If the execution of the loop needs to be terminated at some point, a break statement can be used anywhere within theloop-statement.
The continue statement used anywhere within theloop-statement transfers control toiteration-expression.
A program with an endless loop has undefined behavior if the loop has no observable behavior (I/O, volatile accesses, atomic or synchronization operation) in any part of itscond-expression,iteration-expression orloop-statement. This allows the compilers to optimize out all unobservable loops without proving that they terminate. The only exceptions are the loops wherecond-expression is omitted or is a constant expression;for(;;) is always an endless loop.
As with all other selection and iteration statements, the for statement establishesblock scope: any identifier introduced in theinit-clause,cond-expression, oriteration-expression goes out of scope after theloop-statement. | (since C99) |
attr-spec-seq is an optional list ofattributes, applied to the | (since C23) |
The expression statement used asloop-statement establishes its own block scope, distinct from the scope ofinit-clause, unlike in C++:
for(int i=0;;){long i=1;// valid C, invalid C++// ...}
It is possible to enter the body of a loop usinggoto. When entering a loop in this manner,init-clause andcond-expression are not executed. (If control then reaches the end of the loop body, repetition may occur including execution ofcond-expression.)
Possible output:
Array filled!1 0 1 1 1 1 0 0
C++ documentation for for loop |