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

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

提交回复
热议问题