I am a beginner in C++, and I am wondering how to break out of nested loops. Is there a break(2)?
#include <iostream>
using namespace std;
int main() {
for (int x = 5; x < 10; x++) {
for (int j = 6; j < 9; j++) {
for (int b = 7; b < 12; b++) {
// Some statements
// Is break(2) right or wrong
// or can I use 'break; break;'?
}
}
}
}
You can use goto. It's essentially the same function
#include <iostream>
using namespace std;
int main() {
for(int x = 5; x < 10; x++) {
for(int j = 6; j < 9; j++) {
for(int b = 7; b < 12; b++) {
if (condition)
goto endOfLoop;
}
}
}
endOfLoop:
// Do stuff here
}
No, there is no break(2) unfortunately (or perhaps fortunately, depending on your views of deep nesting of scopes).
There are two main ways to solve this:
break which tells the outer loop to stop.break but also return to jump out. For example:// returns true if should be called again, false if not
bool foo() {
for(int j = 6; j < 9; j++) {
for(int b = 7; b < 12; b++) {
if (something) {
break; // one level
}
if (whatever) {
return true; // two levels
}
if (another) {
return false; // three levels
}
}
}
}
int main() {
for(int x = 5; x < 10; x++) {
if (!foo()) {
break;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With