C++ break, continue and goto
break stops a loop at once. continue skips to the next round.
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) break;
std::cout << i << ' ';
}
std::cout << "\nLoop ended\n";
for (int i = 1; i <= 8; i++) {
if (i % 2 == 0) continue; // skip the even numbers
std::cout << i << ' ';
}
std::cout << '\n';
}
Output
1 2 3 4
Loop ended
1 3 5 7
Search with break
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {4, 9, 15, 22, 31};
int found = -1;
for (std::size_t i = 0; i < numbers.size(); i++) {
if (numbers[i] == 15) {
found = static_cast<int>(i);
break;
}
}
std::cout << "Found at index " << found << '\n';
}
Output
Found at index 2
Leave nested loops
break leaves only the inner loop. To leave all, use a flag, or put the loops in a function and return:
#include <iostream>
bool find_pair(int target) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
if (i * j == target) {
std::cout << "Found " << i << " x " << j << '\n';
return true; // leaves both loops
}
}
}
return false;
}
int main() {
std::cout << std::boolalpha << find_pair(12) << '\n';
}
Output
Found 3 x 4
true
goto
C++ has goto, but it makes code hard to follow. Almost always a loop, a function or break is a better choice.
Note:
A loop condition that says clearly when to stop is better than many break lines. Next: C++ Arrays and std::array.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |