Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: break the main loop

Tags:

c++

loops

break

I am preparing some code:

for(int a = 1; a <= 100; a++)    //loop a (main loop)
{
    for(int b = 1000; b <= 2000; b++)    //loop b
    {
       if(b == 1555)
          break;
    }

    for(int c = 2001; c <= 3000; c++)    //loop c
    {
       .
       .
       .
    }
}

I want to break the main loop (loop variable int a) by using a break; statement in the b loop (loop variable int b).

How can I do it?

like image 533
sundowatch Avatar asked Aug 09 '10 17:08

sundowatch


2 Answers

Use a goto.

for(int a = 1; a <= 100; a++)    //loop a (main loop)
{
    for(int b = 1000; b <= 2000; b++)    //loop b
    {
       if(b == 1555)
          goto loopDone;
    }

    for(int c = 2001; c <= 3000; c++)    //loop c
    {
       .
       .
       .
    }
}
loopDone:
like image 97
Carl Norum Avatar answered Oct 22 '22 05:10

Carl Norum


Either do one of four things: use goto, use throw, use a flag, or refactor.

Many will disagree with using goto, but sometimes it's a clean solution. (Most times, it isn't, but it exists for a reason.) However, I find the use of goto warrants a refactor.

The second solution is to throw some special exception and then catch it just outside the main loop. This is an abuse of the exception system and basically a worse goto; use a goto instead of this.

The third solution would be to use a flag of some sort. This is basically a "safer" goto, but some might argue it's a bit uglier. (Especially with multiple-levels. Though in such a case your concern is how ugly your code is.)

The solution I would recommend is refactor. Whatever you're doing, it's too much. You should move the inner loops into a function, and call that function. Returning to the main loop is simply a return from that function. (In other words "My work is done.")

like image 37
GManNickG Avatar answered Oct 22 '22 04:10

GManNickG