Loops
Loops repeat a block of statements. C provides for for counted iteration, while for "keep going while a condition holds", and do while for bodies that must run at least once.
Detailed Explanation
All three loop forms do the same job and differ only in where the test sits and how much bookkeeping the header holds.
while (cond) { ... } tests before each pass. If the condition is false at the start, the body never runs.
do { ... } while (cond); tests after each pass, so the body always runs at least once. Note the required semicolon. This form is right for "read a command, then decide whether to read another", and wrong for almost everything else, which is why you see it least.
for (init; cond; step) puts the three parts of a counted loop in one place. Any of them may be empty. for (;;) is the conventional infinite loop. The value of the for header is that a reader sees the start, the end, and the increment on one line instead of hunting for the increment somewhere in a thirty-line body.
C99 added the loop-scoped declaration: for (size_t i = 0; i < n; i++). The variable exists only inside the loop, which stops it leaking into the rest of the function and lets you reuse the name in the next loop. C89 required declaring i at the top of the block. Use the C99 form unless you need the final value after the loop, which is the one legitimate reason to declare the counter outside.
break exits the innermost enclosing loop or switch. continue skips to the next iteration. The detail people forget: in a for loop, continue still runs the step expression, but in a while loop it goes straight back to the test, so a continue placed above a hand-written i++ produces an infinite loop.
Boundaries are where loops go wrong. The convention that removes most of the pain is the half-open range [0, n): start at zero, run while the index is strictly less than the count. The count of iterations is then n, with no arithmetic in your head, and concatenating [0, k) with [k, n) covers everything exactly once. Writing i <= n on an array of n elements reads the element one past the end, which is undefined behavior, not a harmless extra read.
The type of the loop variable is not a detail. size_t is unsigned, so it can never be negative, so a countdown written the obvious way never ends:
for (size_t i = n - 1; i >= 0; i--) /* i >= 0 is always true */
When i reaches 0 and decrements, it wraps to SIZE_MAX and the loop continues, indexing far out of bounds. Two fixes work. Either use the post-decrement idiom for (size_t i = n; i-- > 0;), which tests the old value and leaves i one lower inside the body, or use a signed type such as ptrdiff_t when the counter genuinely needs to go negative. A related trap is for (size_t i = 0; i < n - 1; i++) when n is zero: n - 1 wraps to SIZE_MAX and the loop runs essentially forever.
The cost of loops is worth stating plainly. Each iteration is a test and a jump, both cheap and well predicted by the hardware when the pattern is regular. What is not cheap is a body that touches memory in a scattered order, or a loop whose bound the compiler cannot hoist because the body might modify it. Reading a container's length into a local before the loop, when you know it cannot change, is a common and legitimate optimization.
One nuance about infinite loops: C11 allows an implementation to assume a loop terminates when its controlling expression is not a constant expression and the body has no side effects. for (;;) and while (1) use constant expressions and are explicitly exempt, so a deliberate event loop written that way is safe.
Code Examples
#include <stddef.h>
#include <stdio.h>
int main(void) {
const int values[] = {3, 1, 4, 1, 5, 9, 2, 6};
const size_t count = sizeof values / sizeof values[0]; // 8
// Half-open range [0, count). i is scoped to the loop (C99).
long sum = 0;
for (size_t i = 0; i < count; i++) {
if (values[i] % 2 == 0) {
continue; // skip evens; the i++ step still runs
}
sum += values[i];
}
printf("sum of odds = %ld\n", sum); // sum of odds = 23
// Counting down with an unsigned type. Test the old value, then decrement.
// i is count..1 in the test and count-1..0 inside the body.
for (size_t i = count; i-- > 0; ) {
printf("%d ", values[i]);
}
printf("\n"); // 6 2 9 5 1 4 1 3
// BROKEN, do not write this: size_t is unsigned, so i >= 0 never fails.
// for (size_t i = count - 1; i >= 0; i--) { ... }
// while: the test happens first, so an empty range does nothing.
size_t j = 0;
while (j < count && values[j] != 9) {
j++;
}
printf("9 found at index %zu\n", j); // 9 found at index 5
return 0;
}#include <stdio.h>
#include <string.h>
int main(void) {
char line[128];
// do while fits here: we must read once before we can decide to stop.
// Always check the return value of fgets; NULL means EOF or an error.
do {
printf("command> ");
if (fgets(line, sizeof line, stdin) == NULL) {
printf("\ninput closed\n");
break;
}
line[strcspn(line, "\n")] = '\0'; // trim the newline fgets keeps
if (line[0] != '\0') {
printf("you typed: %s\n", line);
}
} while (strcmp(line, "quit") != 0);
return 0;
}Common Gotchas
`i <= n` walks one element past the end
on an array of `n` elements the valid indices are `0` through `n - 1`. Reading or writing `a[n]` is undefined behavior, and it usually corrupts whatever the compiler placed next rather than crashing.
Unsigned counters cannot go below zero
`for (size_t i = n - 1; i >= 0; i--)` never terminates, and `i < n - 1` wraps to a huge bound when `n` is zero. Use `for (size_t i = n; i-- > 0;)` or compute the bound with a signed type.
A stray semicolon empties the loop
`for (int i = 0; i < n; i++);` followed by an indented block runs the block exactly once, after the loop finishes. The compiler will point at this with `-Wempty-body`.
`continue` behaves differently in `while` and `for`
the `for` step expression still runs, a hand-written increment at the bottom of a `while` body does not. Moving a loop from one form to the other requires re-checking every `continue`.