Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

for — loop with initialization, condition, and update

The for loop combines initialization, condition checking, and an update. It repeats a loop body, possibly zero times, and can limit a control variable's scope to the loop.

Version: C23; repository compiler flag, production runtime not attested

Syntax

for (initialization; condition; update) {
    /* body */
}

for initializes once on ordinary entry. Before each execution of its body, it checks a scalar condition: zero ends the loop. The update follows the body, before the next check.

Initialization may be a declaration or expression. An i declared there is available throughout the remaining declaration and the entire loop, but not afterward.

Any header part may be omitted, retaining both semicolons. An omitted condition is always nonzero: for (;;). continue proceeds to the update; break exits the innermost enclosing loop or switch.

The example adds i values from 1 through 4 to sum, producing 10. An accidental semicolon immediately after the header creates an empty body.

Examples

#include <stdio.h>

int main(void)
{
    int sum = 0;
    for (int i = 1; i <= 4; ++i) {
        sum += i;
    }
    printf("%d\n", sum);
    return 0;
}

Result

10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources