do-while, break & continue
A do-while loop always runs at least once. break and continue change the flow inside a loop, and choosing the right loop shape prevents off-by-one bugs.
In plain English
do-while is a ride that always goes once. break gets off, and continue skips to the next turn.
do-while and loop choice
A do-while loop runs its body once and then checks the condition. That makes it a bottom-tested loop. Use for when the iteration count is known, while when it is not, and do-while when the body must run at least once. The update of the loop variable is just as important as the condition.
int attempt = 0;
do {
printf("attempt %d\n", ++attempt);
} while (attempt < 3);break, continue, and increments
break exits the innermost loop or switch immediately. continue skips the rest of the current iteration and goes to the next condition check. Prefix increment ++i changes the value before it is used; postfix i++ uses the old value and then increments. In a loop update the difference rarely matters, but inside an expression it does.
for (int i = 0; i < 10; i++) {
if (i == 3) continue;
if (i == 6) break;
printf("%d ", i);
}Key takeaways
- do-while is bottom-tested and runs at least once.
- break exits the innermost loop.
- continue skips to the next iteration.
- Prefix and postfix increments differ inside expressions.
Common pitfalls
- Using do-while when zero iterations should be allowed.
- Forgetting to update the loop variable and creating an infinite loop.
- Assuming break exits all nested loops.
Key focus
- Know the output difference between while and do-while when the condition starts false.
- Trace break and continue through a loop.
Quick check
1. How many times does the body of do { ... } while (0); execute?
2. What does continue do inside a loop?