How to break out of nested loops?

前端 未结 15 2438
北荒
北荒 2020-11-27 11:21

If I use a break statement, it will only break inner loop and I need to use some flag to break the outer loop. But if there are many nested loops, the code will

相关标签:
15条回答
  • 2020-11-27 12:15

    If you need the values of i and j, this should work but with less performance than others

    for(i;i< 1000; i++){    
        for(j; j< 1000; j++){
            if(condition)
                break;
        }
        if(condition) //the same condition
            break;
    }
    
    0 讨论(0)
  • 2020-11-27 12:16

    Use this wise advice from LLVM team:

    "Turn Predicate Loops into Predicate Functions"

    See:

    http://llvm.org/docs/CodingStandards.html#turn-predicate-loops-into-predicate-functions

    0 讨论(0)
  • 2020-11-27 12:16

    A different approach is to refactor the code from two for loops into a for loop and one manual loop. That way the break in the manual loop applies to the outer loop. I used this once in a Gauss-Jordan Elimination which required three nested loops to process.

    for (int i = 0; i < 1000; i++)
    {
        int j = 0;
    
    MANUAL_LOOP:;
    
        if (j < 1000)
        {
           if (condition)
           {
               break;
           }
    
           j++;
           goto MANUAL_LOOP;
        }
    }
    
    0 讨论(0)
提交回复
热议问题