How can I break out of two nested for loops in Objective-C?

后端 未结 13 591
梦如初夏
梦如初夏 2020-12-01 00:49

I have two for loops nested like this:

for(...) {
    for(...) {

    }
}

I know that there is a break statement. But I am con

相关标签:
13条回答
  • 2020-12-01 01:20

    Probably the easiest way is to use a "flag" variable

    for(i=0; i<10 && (done==false); i++)
      for(j=0;j< 10; j++){
         ..
         ..
         if(...){done=true; break;}
      }
    
    0 讨论(0)
  • 2020-12-01 01:22

    Others have mentioned how you can set a flag or use a goto, but I'd recommend refactoring your code so that the inner loop is turned into a separate method. That method can then return some flag to indicate that the outer loop should break. If you name your methods appropriately, this is much more readable.

    for (int i = 0; i < 10; i++) {
       if (timeToStop(i)) break;
    }
    
    -(bool) timeToStop: (int) i {
        for (int j = 0; j < 10; j++) {
            if (somethingBadHappens) return true;
        }
    
        return false;
    }
    

    Pseudocode, not tested, but you get the idea.

    0 讨论(0)
  • 2020-12-01 01:22

    Another solution is to factor out the second loop in a function:

    int i;
    
    for(i=0; i<10 ; i++){
        if !innerLoop(i) {
            break;
        }
    }
    
    bool innerLoop(int i)
        int j;
        for(j=0;j< 10; j++){
            doSomthing(i,j);
            if(endcondtion){
                return false;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-01 01:24

    break breaks out of one loop, but you can add a check to the outer loop which breaks when the inner breaks.

    bool dobreak = false;
    for ( ..; !dobreak && ..; .. ) {
       for ( ... ) {
          if (...) {
             dobreak = true;
             break;
          }
       }
    }
    
    0 讨论(0)
  • 2020-12-01 01:25

    The break statement only gets you out of the innermost loop. If you don't want the added overhead in code, memory and performance of a dedicated state variable, I recommend refactoring the code out into a function or method of its own, and using return to get out of all the loops:

    void do_lots_of_work(void)
    {
      int i, j;
    
      for(i=0; i<10 ; i++)
      {
        for(j=0;j< 10; j++)
        {
         ..
         ..
         if(disaster_struck())
          return; /* Gets us out of the loops, and the function too. */
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-01 01:25

    The break statement breaks out of the innermost loop. An additional test and break statement would be needed to break out of the outer loop.

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