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?
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:
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.")
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