Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Keywords and Statements

The for statement

Reference for the C for loop: its three clauses, declaring the counter in the loop header, omitting clauses, nested loops and off-by-one pitfalls.

for repeats a statement while a condition holds and packs the three usual loop chores into one header: initialization, test and update. It is the standard way to walk through an array or count a known number of times.

Since C99 the first clause can declare a variable that exists only inside the loop. Any of the three clauses may be left empty; an empty condition means "always true".

C
for (int i = 0; i < n; i++) {
    /* body */
}

Try it

C Counting and walking an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Empty clauses and nested loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
for ( init ; condition ; update ) statement
for ( declaration condition ; update ) statement   /* C99 */
Part Description
init An expression, or (C99) a declaration. Runs once before the first test.
condition Scalar expression tested before every iteration. Empty means true.
update Expression evaluated after each iteration, before the next test.
statement The body, normally a block.

Equivalent form: init; while (condition) { body; update; }, except that continue jumps to update.

Undefined behavior: modifying the counter in a way that overflows a signed integer (for example looping with i <= INT_MAX) is undefined, and the loop may then be optimized in surprising ways.

Usage notes

  • Off by one. For n elements use i < n, starting at 0. Using <= reads one element past the end of the array.
  • Counting down with unsigned types never ends: for (size_t i = n - 1; i >= 0; i--) is always true. Use for (size_t i = n; i-- > 0; ) instead.
  • Floating-point counters accumulate rounding error. Loop on an integer and compute the value from it.
  • Scope of the counter. A counter declared in the header disappears after the loop. Declare it earlier if you need its final value.
  • continue skips the rest of the body but still runs update; break leaves the loop. See break and continue.
  • A stray semicolon (for (...);) makes the body empty, and the next block runs once.
  • Modifying the counter inside the body works but surprises readers; prefer a while loop when the step is irregular.
  • Comma operator: i++, j-- in the update is the usual way to move two variables (comma operator).