Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you break out of nested loops in C++? [duplicate]

Tags:

c++

break

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;'?
            }
        }
    }
}
like image 207
Ian Avatar asked Oct 21 '25 06:10

Ian


2 Answers

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
}
like image 170
Dillydill123 Avatar answered Oct 23 '25 20:10

Dillydill123


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;
        }
    }
}
like image 38
John Zwinck Avatar answered Oct 23 '25 18:10

John Zwinck