Post

How to exit nested loops

How to exit nested loops

Introduction

Recently when solving 999. Available Captures for Rook, I need to exit nested for loops. In C++, there seems not a better way to do it.

After searching google for a while, I found this.

Use a bool flag

You have to check the specific flag at the end of each for loop.

1
2
3
4
5
6
7
8
for (int i = 1; i < 3; ++i) {
    for (int j = 1; j < 3; ++j) {
        if (i+j == 2) {
            exited = true;break;
        }
    }
    if (exited) break;
}

Use goto

1
2
3
4
5
6
for (int i = 1; i < 3; ++i) {
    for (int j = 1; j < 3; ++j) {
        if (i+j == 2) goto EXIT;
    }
}
EXIT: int bingo = 1;

Usually goto means bad things, so use it at your own risk.

Use lambda function

This is very interesting. I have been using a lot of lambdas in the code when sovling leetcode problems. It will make the code short:

  • no need to define another function outside current function
  • no need to pass arguments around as you can capture them in the closure

Use & to capture the value

1
2
3
4
5
6
7
8
9
// We assume you need the value of `i` and `j`.
int i, j;
[&](){
    for (i = 0; i < 3; ++i) {
        for (j = 0; j < 3; ++j) {
            if (i + j == 2) return;
        }
    }
}(); // remember to call the lambda function.
This post is licensed under CC BY 4.0 by the author.