A for loop places initialization, continuation testing, and iteration update in its control statement around a loop body. The body performs the work; the update must move the control value toward termination. section 12.2
Read a for loop as four connected parts:
- Initialization establishes the loop’s preconditions, often by declaring and setting the control variable. section 12.2
- The continuation test decides whether the body executes; the update then changes the control value after each iteration. section 12.2
- Keep loop variables close to their use; declaring one in the for statement limits its scope and reduces reasoning distance. section 5.1
- Treat macros that hide initialization, testing, and updating cautiously: textual substitution can obscure compiler errors and introduce a stray semicolon. section 5.2
The continue mistake
In a for loop, continue transfers control to the update section before the next continuation test. Moving equivalent code into a while loop without manually updating the control variable can create an infinite loop. For example, when x is not divisible by 3, while (x > 0) { if (x % 3 != 0) continue; ... --x; } never changes x. Add --x before continue, or preserve the for loop’s update behavior explicitly. section 12.2
Listing 12.3 A while loop with a continue keyword
int main() {
int x = 10;
while (x > 0) {
if (x % 3 != 0)
continue; #1
std::cout << x << " is divisible by 3\n";
--x;
}
return 0;
}
Inspect the looping error in a concrete while-loop listing, then compare its control flow with the for-loop rule. section 12.2
Listing 12.4 Properly executing the update section before the continue keyword
int main() {
int x = 10;
while (x > 0) {
if (x % 3 != 0) {
--x; #1
continue;
}
std::cout << x << " is divisible by 3\n";
--x;
}
return 0;
}
Inspect the corrected listing, which performs the missing update before continuing. section 12.2


























