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

后端 未结 13 589
梦如初夏
梦如初夏 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:03

    Exactly like the last ones are, generally like this:

    for(i=0;i<a;i++){  
     for(j=0;j<a;j++){
      if(Something_goes_wrong){
       i=a;
       break;
       }
     }
    }
    
    0 讨论(0)
  • 2020-12-01 01:04

    The break statement will only break out of the loop in scope, which is the parent loop. If you want to break out of the second loop as well you could use a boolean variable which is in scope of both loops

    bool isTerminated = false;
    
    for (...)
    {
        if (!isTerminated)
        {
            for(...)
            {
                ...
    
                isTerminated = true;
                break;
            }
        }
        else
        {
            break;
        }
    }
    
    0 讨论(0)
  • 2020-12-01 01:05

    Other than the already mentioned flag variable or goto you could throw an Objective-C exception:

    @try {
      for() {
        for() {
           @throw ...
        }
      }
    }
    @catch{
      ...
    }
    
    0 讨论(0)
  • 2020-12-01 01:07

    If using goto simplifies the code, then it would be appropriate.

    for (;;) 
    {
        for (;;) 
        {
            break; /* breaks inner loop */
        } 
        for (;;) 
        {
            goto outer; /* breaks outer loop */
        }
    } 
    outer:;
    
    0 讨论(0)
  • 2020-12-01 01:17

    Change top loop's counter before break

    for(i=0; i<10 ; i++)
      for(j=0;j< 10; j++){
         ..
         ..
         i = 10; 
         break;
      }
    
    0 讨论(0)
  • 2020-12-01 01:18

    Just for grins, how about changing this true/false check into a method and using return statements:

    - (bool) checkTrueFalse: parameters{
    
       for ( ...) {
          for ( ... ) {
    
             if (...) {
                return true;
             }
    
          }
       }
       return false;
    }
    
    0 讨论(0)
提交回复
热议问题