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

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

    I'd do something like:

      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) {
                      return;
                  }
              }
          }
      }
    
    0 讨论(0)
  • 2020-12-28 20:07

    How would you accomplish the same thing? (w/o using jumps)

    Why? Nothing is universally evil, and every put-upon tool has its uses (except gets()). Using goto here makes your code look cleaner, and is one of the only choices we have (assuming C). Look:

    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) {
                    goto END;
                }
            }
        }
    }
    END:
    

    Much cleaner than all those flag variables, and it even shows more clearly what your code is doing.

    0 讨论(0)
提交回复
热议问题