What if I have nested loops, and I want to break out of all of them at once?
while (true) { // ... while (shouldCont) { // ... while (shouldGo) { // ... if (timeToStop) { break; // Break out of everything? } } } }
In PHP, break
takes an argument for the number of loops to break out of. Can something like this be done in C#?
What about something hideous, like goto
?
// In the innermost loop goto BREAK // ... BREAK: break; break; break;
Another way of breaking out multiple loops is to initialize a flag variable with a False value. The variable can be assigned a True value just before breaking out of the inner loop. The outer loop must contain an if block after the inner 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.
The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.
There are two steps to break from a nested loop, the first part is labeling loop and the second part is using labeled break. You must put your label before the loop and you need a colon after the label as well. When you use that label after the break, control will jump outside of the labeled loop.
Extract your nested loops into a function and then you can use return to get out of the loop from anywhere, rather than break.
Introduce another control flag and put it in all your nested while condition like below. Also replaces the while(true) condition you have with that
bool keepLooping = true; while (keepLooping) { // ... while (shouldCont && keepLooping) { // ... while (shouldGo && keepLooping) { // ... if (timeToStop) { keepLooping = false; break; // break out of everything? } } } }
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