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

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

    If you are using GCC and this library, the break can accept the number of nested loops you want to exit:

    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(3);
                }
            }
        }
    }
    

提交回复
热议问题