Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of multiple loops at once in C#?

Tags:

c#

loops

break

goto

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; 
like image 790
Nick Heiner Avatar asked Feb 26 '10 02:02

Nick Heiner


People also ask

How do you break multiple while loops?

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.

Does Break Break Out of all loops in C?

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 many loops does break break C?

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.

How do I get out of a nested loop?

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.


2 Answers

Extract your nested loops into a function and then you can use return to get out of the loop from anywhere, rather than break.

like image 192
Michael Anderson Avatar answered Sep 28 '22 21:09

Michael Anderson


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?             }         }       } } 
like image 41
Fadrian Sudaman Avatar answered Sep 28 '22 23:09

Fadrian Sudaman