What is a neat way of breaking out of many for loops at once?

后端 未结 14 1426
既然无缘
既然无缘 2020-12-28 19:33

Suppose I need to break out of three or four nested for loops at once at the occurence of some event inside the innermost loop. What is a neat way of doing that?

相关标签:
14条回答
  • 2020-12-28 19:49

    If premature completion of any cycle always means that you have to break the enclosing cycle as well, then you don't need any extra flags. The whole thing might just look as follows

    int i, j, k;
    for (i = 0; i < 100; i++) {
        for (j = 0; j < 100; j++) {
            for (k = 0; k < 100; k++) {
                if (k == 50)
                    break;
            }
            if (k < 100) break;
        }
        if (j < 100) break;
    }
    

    In my experience, this is what is needed in majority of cases.

    0 讨论(0)
  • 2020-12-28 19:51

    Put all the loops in a function and just return instead of break.

    0 讨论(0)
  • 2020-12-28 19:51

    sometimes you can use trick like this:

    for (i = 0; i < 100 && !flag2; i++) {
    for (j = 0; j < 100 && !flag1; j++) {
        for (k = 0; k < 100; k++) {
            if (k == 50) {
                k = 100;
                i = 100;
                j = 100;
            }
        }
    }
    

    }

    or declare addition flag in your loop:

    bool end = false;
    for(int i =0; i < 1000 && !end; i++) {
       //do thing
       end = true;
    }
    

    it costs only a line but clean, I think.

    justin

    0 讨论(0)
  • 2020-12-28 19:51

    a little bit of silly self-documenting:

    int i, j, k;
    int done = 0;
    
    for (i = 0; i < 100 && ! done; i++) {
        for (j = 0; j < 100 && ! done; j++) {
            for (k = 0; k < 100 && ! done; k++) {
                if (k == 50) we_are(done);
            }
        }
    }
    
    //...
    
    void we_are(int *done) {
        *done = 1;
    }
    

    but really, you shouldn't have three nested for-loops. You should consider refactoring into different functions and improving your program's logic instead of doing this.

    While I agree that sometimes goto really is the best solution, I think that any problem to which goto is the solution is a result of poor code.

    0 讨论(0)
  • 2020-12-28 19:52

    use goto. it's clean and simple.

    0 讨论(0)
  • 2020-12-28 20:00

    Just a wee bit better.

    int i, j, k;
    int flag1 = 0;
    int flag2 = 0;
    
    for (i = 0; i < 100 && !flag2; i++) {
        for (j = 0; j < 100 && !flag1; j++) {
            for (k = 0; k < 100; k++) {
                if (k == 50) {
                    flag1 = 1;
                    flag2 = 1;
                    break;
                }
            }
        }
    }
    

    But if you really need to have those loops, then it makes sense explicitly declaring in each loop what conditions must hold for it to continue, for readability.

    0 讨论(0)
提交回复
热议问题