Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get out of multiple loops? [duplicate]

People also ask

How do you break out of all loops?

Method 1: Using the return statement Define a function and place the loops within that function. Using a return statement can directly end the function, thus breaking out of all the loops.

How do you stop a nested loop?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

How do you exit a double loop in Python?

Break out of nested loops with a flag variableIn the condition that the inner loop ends with break , set the flag to True , and in the outer loop, set break according to the flag.


A very elegant solution to this is to move the entire nest of loops to a separate method and return; when you want to break out of all loops.


A goto is perfectly fine here:

foreach (___)
{
    foreach (___)
    {
        if (condition)
        {
            goto done;
        }
    }
}
done: ;

The best way is probably to refactor to smaller methods with return statements. But if you need a lot of variables in scope you can always use a delegate.

   Action work = delegate
        {
            foreach (___)
            {
                 foreach (___)
                 {
                       foreach (___)
                       {
                            if (condition)
                            {
                                 return;
                            }
                       }
                  }
             }

        };

  work();

Years ago, when I was in school, we had informatics with a pretty out of the books stupid teacher. One rule was "no goto". I had an algorithm with multiple loops that grew to many times the size without goto.

There are good reasons, and breaking out of multiple loops is one.


Maybe this is the only valid reason to use goto.


bool bLoopBreak = false;

foreach (___)
{
    foreach (___)
    {
        foreach (___)
        {
            if (condition)
            {
                bLoopBreak = true;
                break;
                //break out of all loops
            }
        }
        if (bLoopBreak) break;
    }
    if (bLoopBreak) break;
}