C++ Break and Continue
break leaves a loop at once; continue skips the rest of the current round and starts the next one.
break: stop when found
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {4, 9, 15, 22, 8};
for (std::size_t i = 0; i < numbers.size(); i++) {
if (numbers[i] > 10) {
std::cout << "First number above 10: " << numbers[i]
<< " at position " << i << "\n";
break;
}
}
return 0;
}First number above 10: 15 at position 2
std::size_t is the unsigned type of sizes and indexes, the type size() returns; using it for the index avoids a warning about comparing signed and unsigned numbers.
continue: skip some rounds
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) continue; // skip multiples of 3
std::cout << i << " ";
}
std::cout << "\n";
return 0;
}1 2 4 5 7 8 10
In a while loop, continue jumps straight to the condition, so make sure the loop variable has already changed, or the loop never ends.
A loop that ends with break
#include <iostream>
int main() {
int total = 0;
while (true) {
int n;
std::cout << "Number (0 to stop): ";
if (!(std::cin >> n) || n == 0) break;
total += n;
}
std::cout << "\nTotal: " << total << "\n";
return 0;
}5 12 0
Number (0 to stop): Number (0 to stop): Number (0 to stop): Total: 17
Nested loops
break and continue affect only the innermost loop. To leave several loops at once, move them into a function and return, or use a flag:
#include <iostream>
bool findPair(int target) {
for (int a = 1; a <= 9; a++) {
for (int b = a; b <= 9; b++) {
if (a * b == target) {
std::cout << a << " x " << b << " = " << target << "\n";
return true; // leaves both loops
}
}
}
return false;
}
int main() {
if (!findPair(42)) std::cout << "none\n";
return 0;
}6 x 7 = 42
Using them well
break and continue make loops shorter when they express a clear rule: "stop at the first match", "skip invalid entries". Too many of them in one loop make it hard to see when the loop really ends. If a loop has several exits, consider moving it into a function that returns the result, or let the loop condition say when to stop.
When the goal is only to find something, the standard library often does it for you: std::find_if returns the first element that matches a condition (see Algorithms), with no loop to write at all.
A break inside a switch that sits inside a loop ends only the switch, not the loop. To leave the loop from inside a switch, use a flag that the loop condition checks, or return from the function.
Practice exercises
- Print the numbers from 1 to 50, stopping at the first one divisible by both 4 and 6.
- Print the numbers from 1 to 20 except the multiples of 5.
- Find the first pair of numbers from 1 to 20 whose squares add up to 100.