Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate outer loop in nested loops?

What is the best way to terminate all nested loops in the example below. Once the if statement is true, I want to terminate the outer for statement (with I). In the other words I need the whole loop to stop. Is there better way than setting I to 10?

for (int I = 0; I < 10; I++)
{
    for (int A = 0; A < 10; A++)
    {
        for (int B = 0; B < 10; B++)
        {
            if (something)
                break;
        }
    }
}
like image 422
Mirial Avatar asked Jun 01 '11 12:06

Mirial


People also ask

How can you break out of a for loop inside 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.

Does continue break out of outer loop?

You can break all loops with else and continue . The code with explanation is as follows. When the inner loop ends normally without break , continue in the else clause is executed. This continue is for the outer loop, and skips break in the outer loop and continues to the next cycle.


1 Answers

I would refactor this to a method, and just call return whenever I need to.

You could also use goto, and I have used goto for this, but it gets frowned upon. Which is dumb; this scenario is why it exists in the language.

void DoSomeStuff()
{
    for (int I = 0; I < 10; I++)
    {
        for (int A = 0; A < 10; A++)
        {
            for (int B = 0; B < 10; B++)
            {
                if (something)
                    return;
            }
        }
    }
}
...somewhere else...
DoSomeStuff();
like image 137
Marc Gravell Avatar answered Oct 03 '22 15:10

Marc Gravell