Summary#
for (init; cond; update) { … } is the C-style counting loop. It runs init once, then repeats the body
as long as cond holds, running update after each pass. Any of the three header clauses may be omitted;
for (;;) is an infinite loop (exit it with break). continue runs the update before re-testing the
condition — the same as C#.
Signature#
for (<init>; <cond>; <update>) {
…
}
// init: a declaration (loop-scoped) or an expression, or empty
// cond: a Boolean expression, or empty (= always true)
// update: an expression run after each iteration, or emptyDescription#
initruns once before the loop. A declaration there (int i = 0) is scoped to the loop — it is not visible after thefor.condis re-tested before each iteration; an empty condition is always true (for (;;)).updateruns after each body pass and oncontinue— socontinueadvances the counter, it does not skip it. (This is whyforis a first-class construct, not awhilerewrite.)breakexits the loop;continuejumps to the update then the next condition test.- The
updateis typicallyi++ori += n(see ++ / -- (increment / decrement) / Compound assignment (+= -= *= /= %= ??=)). - Durable: a suspend inside a
forbody survives serialize/restore — the loop resumes at the right iteration and still runs its update.
Examples#
int Sum() { int s = 0; for (int i = 0; i < 10; i++) { s = s + i; } return s; } // 45
// continue still runs the update — sums the even indices (no infinite loop).
int Evens() {
int s = 0;
for (int i = 0; i < 10; i++) {
if (i % 2 == 1) { continue; }
s = s + i;
}
return s; // 0+2+4+6+8 = 20
}
// Nested loops.
int Grid() {
int s = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) { s = s + i * j; }
}
return s; // 9
}
// Infinite for + break (counter advanced in the body).
int Countdown() {
int i = 0;
for (;;) { if (i >= 7) { break; } i++; }
return i; // 7
}See also#
- while — the condition-only loop
- foreach — iterate a collection's elements
- ++ / -- (increment / decrement) — the usual
updateclause - break / continue — loop control