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

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

    If you absolutely don't want to use goto, set all loop conditions to false:

    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) {
                    i = j = k = INT_MAX;
                    break;
                }
            }
        }
    }
    

    note: a smart optimizing compiler will turn the contents of the if in a jump to the end of the outer-most loop

提交回复
热议问题