C++•Loop Control
C++ Break and Continue Loop Control Statements
break exits the enclosing loop; continue jumps directly to the loop update step.
Syntax
if (condition) break;
if (condition) continue;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| break | Statement | Terminates innermost loop immediately. |
| continue | Statement | Skips remainder of current iteration. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C++ locally:
#include <iostream>
#include <vector>
int main() {
std::vector<int> packetCodes = {200, 204, -1, 301, 500, 200};
std::cout << "Processing packets:\n";
for (int code : packetCodes) {
if (code < 0) {
std::cout << " [SKIP] Corrupt packet " << code << "\n";
continue; // Skip rest of iteration
}
if (code == 500) {
std::cout << " [HALT] Fatal 500 error encountered! Terminating.\n";
break; // Stop loop
}
std::cout << " [OK] Processed packet: " << code << "\n";
}
return 0;
}Expected Output:
Processing packets: [OK] Processed packet: 200 [OK] Processed packet: 204 [SKIP] Corrupt packet -1 [OK] Processed packet: 301 [HALT] Fatal 500 error encountered! Terminating.
How It Works: Step-by-Step
- Lines 10-13: continue skips -1 without processing.
- Lines 14-17: break halts loop immediately upon code 500.
Key Concepts
- continue skips to the loop update expression in for loops.
- break terminates only the innermost loop in nested structures.
Common Mistake: Using continue in a while loop before incrementing counter
Skipping the increment step in a while loop leads to an infinite loop.
❌ Incorrect
while (i < 5) {
if (i == 2) continue; // i is never incremented!
++i;
}✅ Correct
while (i < 5) {
if (i == 2) { ++i; continue; }
++i;
}Related C++ Tutorials & Compiler
C++ For Loops and Range-Based For Loops (C++11)
Master traditional counter loops and modern C++11 range-based for loops over collections.
C++ While and Do-While Loops with Examples
Learn pre-test while loops and post-test do-while loops in C++.
C++ If...Else Statements and Boolean Logic with Examples
Learn decision-making structures in C++ with if, else if, else, and C++17 init-statements.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.