Namespaces
Variants
Views
Actions

for loop

From cppreference.com
< c‎ | language
Revision as of 14:30, 19 January 2013 by Pedro (Talk | contribs)

Executes a loop.

Used as a shorter equivalent of while loop.

Contents

Syntax

for ( Template:sparam ; Template:sparam ; Template:sparam ) Template:sparam

Explanation

Unless there are any continue statements, the above syntax produces code equivalent to:

{
Template:sparam ;
while ( Template:sparam ) {
Template:sparam
Template:sparam ;
}

}

The Template:sparam is executed before the execution of the loop. The Template:sparam shall evaluate to value, convertible to bool. It is evaluated before each iteration of the loop. The loop continues only if its value is true. The Template:sparam is executed on each iteration, after which Template:sparam is executed.

If the execution of the loop needs to be terminated at some point, break statement can be used as terminating statement.

If the execution of the loop needs to be continued at the end of the loop body, continue statement can be used as shortcut. When there are continues in the loop body (Template:sparam), then each continue passes control to the Template:sparam instead of passing to the next iteration. This way, at each iteration Template:sparam is guaranteed to be executed (unless we break out of the loop).

Keywords

for

Example

The following example demonstrates the usage of the for loop in an array manipulation

#include <stdio.h>
#include <stdlib.h>
 
#define SIZE 8
 
int main (int argc, char **argv)
{
    unsigned i = 0, array [SIZE];
 
    for( ; i < SIZE; ++i)
        array [i] = random() % 2;
 
    printf("Array filled!\n");
 
    for (i = 0; i < SIZE; ++i)
        printf("%d ", array[i]);
 
    printf("\n");
 
    return EXIT_SUCCESS;
}

Output:

Array filled!
1 0 1 1 1 1 0 0