Break exits from the innermost loop.
so
1 2 3 4 5 6 7 8
|
while(cond)
{
while(cond2)
{
if(bad)
break; //stops this while loop, resumes outer while loop.
}
}
| |
that concept can be paired with conditionals:
1 2 3 4 5 6 7 8 9 10 11
|
while(cond && didbreak) //won't resume, because you set the bool below
{
while(cond2)
{
if(didbreak = bad) //bad can be a bool expression
{
break; //stops this while loop, resumes outer while loop.
}
}
if(didbreak) continue; //if there is more code after the inner while loop.
}
| |
this gets kind of hairy beyond 3 or so nested loops. if you are really, really deep, goto is a fine option: every other option requires more lines of code and twisting to get to the same place.
1 2 3 4 5 6 7 8 9
|
while(first)
while(second)
while(third)
while(forth)
{
if(bigproblem)
goto getout;
}
getout: ;
| |
I believe you can also rig error handling to get out, if you want to slightly misuse the concept. error handling is a powerful hack that is frowned upon for use outside of actual error handling, but it CAN be used for things like this or other weird constructs to avoid tying yourself into a knot to express your idea. Here is an example of it
https://cplusplus.com/forum/lounge/154085/. As noted there, misuse of error handling is both inefficient as well as questionable design/style/approach.
often nested loops are just handy but not necessary, for example iterating over a multi-d array. if you re-rig it for 1d single loop, its easier to get out of there, and its often trivial to do that.