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

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

    goto. This is one of the very few places where goto is the appropriate tool, and is usually the argument presented why goto isn't complete evil.

    Sometimes, though, I do this:

    void foo() {
        bar_t *b = make_bar();
        foo_helper(bar);
        free_bar(b);
    }
    
    void foo_helper(bar_t *b) {
        int i,j;
        for (i=0; i < imax; i++) {
            for (j=0; j < jmax; j++) {
                if (uhoh(i, j) {
                    return;
                }
            }
        }
    }
    

    The idea is that I get a guaranteed free of bar, plus I get a clean two-level break out of the switch via return.

提交回复
热议问题