Ch3.7: continue
The continue Statement
A continue statement skips the rest of the loop body and jumps
directly to the next iteration.
continue;
It does not exit the loop. It only skips the remaining statements in the current iteration.
continue in a while Loop
This loop prints only even numbers.
::std::uint_least32_t i{};
while (i != 10) {
if (i % 2 == 1) {
++i;
continue; // skip odd numbers
}
println("even: ", i);
++i;
}
continue in a for Loop
continue jumps directly to the loop’s step expression.
for (::std::uint_least32_t i{}; i != 10; ++i) {
if (i % 3 != 0) {
continue; // skip non-multiples of 3
}
println("multiple of 3: ", i);
}
continue in Dead Loops
In a dead loop, continue simply restarts the loop.
::std::uint_least32_t i{};
for (;;) {
++i;
if (i < 5) {
continue; // restart the loop
}
println("i reached 5");
break; // stop the loop
}
continue with Init-statement Loops
continue behaves normally even when the loop uses an init-statement.
for (auto i = 0; i < 10; ++i) {
if (i == 4) {
continue;
}
println("i=", i);
}
Nested Loops
continue affects only the innermost loop.
for (::std::uint_least32_t i{}; i != 3; ++i) {
for (::std::uint_least32_t j{}; j != 3; ++j) {
if (j == 1) {
continue; // skips only the inner loop's iteration
}
println("i=", i, ", j=", j);
}
}
Pseudo-graph: Where continue Goes
┌───────────────┐
│ loop │
│ begins │
└───────┬───────┘
│
▼
┌───────────────┐
│ cond │─── false ───▶ loop ends
└───────┬───────┘
│ true
▼
┌───────────────┐
│ body │
└───────┬───────┘
│
├──▶ if (continue) ───────▶ step ─────▶ cond
│
▼
┌───────────────┐
│ step │
└───────┬───────┘
│
└─────────────── back to cond
Key takeaways
- continue skips the rest of the loop body: it does not exit the loop.
- continue jumps to the next iteration: in
for, it jumps to the step expression. - Nested loops: only the innermost loop is affected.
- Dead loops:
continuesimply restarts the loop. - Clarity: use
continueintentionally; avoid hiding it deep inside complex logic.