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

后端 未结 14 1504
既然无缘
既然无缘 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: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.

提交回复
热议问题