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

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

    Dividing by 0 is the surest method I know that will break you out of any number of loops. This works because the DIV assembly instruction doesn't like such silliness.

    So, you can try this:

    int i, j, k;
    int flag1 = 0;
    int flag2 = 0;
    
    for (i = 0; i < 100; i++) {
        for (j = 0; j < 100; j++) {
            for (k = 0; k < 100; k++) {
                if (k == 50) {
                    flag1 = 1;
                    flag2 = 1;
                    int z = 1 / 0;  // we're outta here!!!
                }
            }
            if (flag1 == 1)break;
        }
        if (flag2 == 1)break;
    }
    

    Getting back from the trap that happens on such events left as an exercise for the reader (it's trivial).

提交回复
热议问题