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

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

提交回复
热议问题