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".
for (int i = 0; i < n; i++) { /* body */ }
Try it
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.
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
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
nelements usei < n, starting at0. 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. Usefor (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.
continueskips the rest of the body but still runsupdate;breakleaves 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
whileloop when the step is irregular. - Comma operator:
i++, j--in the update is the usual way to move two variables (comma operator).
Related
whileanddo-while,breakandcontinue, arrays- Lessons: for loops, while loops