Break and Continue
C++ Break and Continue
Definition: Loop control statements like break and continue allow you to alter the flow of a loop based on specific conditions. They provide a way to exit a loop prematurely or skip specific iterations without stopping the entire loop process.
Why: In any professional C++ syllabus, break and continue are treated as essential tools for optimizing code. They allow you to handle exceptions within a loop—such as stopping a search once a value is found or skipping invalid data points during a calculation.
The Two Control Keywords
While both keywords affect how a loop runs, they serve very different purposes in logic building:
The Break Statement
The break statement is used to "jump out" of a loop entirely. It immediately terminates the loop and moves the program to the next line of code outside the loop block.
The Continue Statement
The continue statement breaks one iteration in the loop if a specified condition occurs, and continues with the next iteration in the loop.
Example: Skipping a Specific Number
In this example, we use the continue keyword to skip the number 3 while printing a sequence from 1 to 5:
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // Skips the rest of the code for i=3 } cout << i << endl; } // Output: 1, 2, 4, 5 return 0; }
Comparison Table
| Feature | Break | Continue |
|---|---|---|
| Execution Flow | Exits the loop body completely. | Jumps to the next iteration (the increment part). |
| Typical Use Case | Stopping a search once a result is found. | Filtering out unwanted values (like avoiding division by zero). |
| Scope | Can be used in loops and switch statements. | Only used within loops. |
Key Notes
- The Break in Switch: You have already seen
breakinswitchstatements. Its job there is identical: it stops the program from "falling through" to the next case. - Infinite Loop Safety: When using
continuein awhileloop, ensure that the counter variable (likei++) is updated before thecontinuestatement. Otherwise, the program may skip the increment and get stuck in an infinite loop. - Nested Loop Behavior: A
breakorcontinueonly affects the innermost loop it is currently in. If you have a loop inside a loop, breaking the inner one will not stop the outer one.
🏋️ Test Yourself With Exercises
Take our quiz on Break and Continue to test your knowledge.
Browse Quizzes »