Moving to next iteration of external loop from inside the nested loop Directly

Viewed 639

I have a nested loop and in the internal loop I am doing a condition check and if that condition check Is satisfied i want to jump to the next iteration of the external loop.

It goes something like this

for( int i = 0 ; i < n ; i++ ){
    for( int j = 0 ; j < n ; j++ ){
            if( condition ){
                // Move to next iteration of first or external loop 
                // skip the work and work2 both
            }
            // some work being done
            work(); 
        }
        work2(); 
}

What I mean here is If the condition is satisfied at i = 2 and j = 5
I want to move to i = 3

Is there any way to do without using Booleans something similar to the break statement ?

3 Answers

Apart from what was pointed out in the comments, which is to force the value of j, you can use a lambda and call it inline. It's a bit ugly but does the job:

for( int i = 0 ; i < n ; i++ ){
    [&]() // OR [=]() OR [i, n]() depending on your usage
    {
        for( int j = 0 ; j < n ; j++ ){
            if( condition ){
                return;
            }
            // some work being done
            work(); 
        }
    }();
}

You can put the condition part in inner for-loop iteration check part.

As following:

for( int i = 0 ; i < n ; i++ )
{
    for( int j = 0 ; (j < n) && conditionCheckFunction() ; j++ )
    {
        work(); 
    }
}  

If your condition is satisfied, just break out of the inner loop. The control flow will then go to the next iteration of the outer loop:

for(int i = 0 ; i < n ; i++) {
    for(int j = 0 ; j < n ; j++) {
        if( condition ) {
            break;  // out of inner loop
        }
        work(); 
    }
}
Related