Executes a loop.
Used as a shorter equivalent of while loop.
for ( init_clause ; cond_expression ; iteration_expression ) loop_statement |
Behaves as follows:
auto
and register
storage classes are allowed for the variables declared in this declaration. init_clause, cond_expression, and iteration_expression are all optional:
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 the loop_statement.
The continue statement used anywhere within the loop_statement transfers control to iteration_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 its cond_expression, iteration_expression or loop_statement. This allows the compilers to optimize out all unobservable loops without proving that they terminate. The only exceptions are the loops where cond_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 establishes block scope: any identifier introduced in the init_clause, cond_expression, or iteration_expression goes out of scope after the loop_statement. | (since C99) |
for
.
The expression statement used as loop_statement establishes its own block scope, distinct from the scope of init_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 using goto. In this case, init_clause and cond_expression are not executed.
#include <stdio.h> #include <stdlib.h> enum { SIZE = 8 }; int main(void) { int array[SIZE]; for(size_t i = 0 ; i < SIZE; ++i) array [i] = rand() % 2; printf("Array filled!\n"); for (size_t i = 0; i < SIZE; ++i) printf("%d ", array[i]); printf("\n"); }
Possible output:
Array filled! 1 0 1 1 1 1 0 0
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/c/language/for