Can someone tell me how to break the main loop when I have nested loops?
Example*:
/*Main loop*/
for(int y = 0; y < 100; y+=10)
{
/*Sub loop*/
for (int x = 0; x < 100; x += 10)
{
if(x == 60)
{
//Break the main loop
}
}
}
*This code do nothing, it's just an example
What should I put in the place of the "Break main loop" comment? In java there are labels which I can break (when i set a label to the main loop named "MainLoop" I can write "break MainLoop;" and it will be valid), but what can I do here?
Thanks in advise!
The outer loop must contain an if block after the inner loop. The if block must check the value of the flag variable and contain a break statement. If the flag variable is True, then the if block will be executed and will break out of the inner loop also.
if is not a loop in any programming language(not in C++ either). If-else statements are conditional statements where you take some actions if a predefined condition is true or false. There is no loop in if statements. So you can't break if statement since it is not a loop or switch statement.
Break Statement is a loop control statement that is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop.
goto
!
I fail to understand this persistent meme which says that goto
is considered "harmful". When used correctly, it is very powerful, and this is such a case.
Some people would shoot me for suggesting the use of the goto
statement, but breaking out of multiple loops is one of the places it can be very useful (and efficient):
/*Main loop*/
for(int y = 0; y < 100; y+=10)
{
/*Sub loop*/
for (int x = 0; x < 100; x += 10)
{
if(x == 56)
{
goto MainLoopDone;
}
}
}
MainLoopDone:
// carry on here
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