2

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;'?
            }
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ian
  • 687
  • 3
  • 8
  • 17

2 Answers2

10

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
}
Quentin
  • 62,093
  • 7
  • 131
  • 191
Dillydill123
  • 693
  • 7
  • 22
4

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:

  1. Set a flag before you break which tells the outer loop to stop.
  2. Put some of your nested loops into functions, so that they can do 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;
        }
    }
}
John Zwinck
  • 239,568
  • 38
  • 324
  • 436