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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With