Loop Control Statements
Lesson outline
Introduction to Loop Control
C++ provides statements that alter normal loop execution:
break: exits a loop (or aswitch) immediatelycontinue: skips to the next iteration of the nearest enclosing loopgoto: jumps to a labeled statement (generally discouraged due to readability and safety issues)
Note: continue is valid only inside loops; break works in loops and switch.
break Statement
The break statement immediately ends the nearest enclosing loop or switch, transferring control to the statement following it.
continue Statement
The continue statement skips the remaining code in the current iteration and starts the next loop iteration.
In a for loop, the increment expression runs after continue and before the next condition check. In while/do-while, you must ensure loop variables are updated before continue to avoid infinite loops.
Nested Loop Control
Loop control statements affect only the innermost loop in which they appear, unless additional logic is used to break outer loops.
Switch Inside Loops: break vs continue
Inside a loop, break breaks only the switch (not the loop). continue skips to the next loop iteration even if it appears inside a switch.
goto (Use Sparingly)
goto can be used for single-point cleanup in low-level code, but modern C++ prefers RAII (e.g., smart pointers, containers) to manage resources safely.
C++ forbids jumping into a scope in a way that skips initialization of variables with automatic storage.
Best Practices
- Use
breakandcontinueonly when they make control flow clearer. - Avoid
gotoin C++; favor RAII and structured control flow. - When
continueappears inwhile/do-while, ensure loop variables are updated beforehand. - Clearly document any non-obvious early exits to improve readability.
Common Pitfalls
- Assuming
breakinside aswitchbreaks the outer loop (it does not). - Using
continueinside awhilewithout updating the loop variable first, causing an infinite loop. - Confusing
continuein aswitchinside a loop: it continues the loop, not the switch.