In fact, that task can be easily accomplished using goto statement. You can’t use break statement because it only breaks the innermost loop.
However, many programmers hear the myth that goto statement is very bad, buggy, obsolete, etc. so they want to avoid using it.
So, how to break nested loops in C++, without the mystical GOTO statement? If it were used, the code would be something like this.
while (expression1)
{
while (expression2)
{
// do something
goto out;
}
}
out:
;
In my opinion, the above code is clear enough to be implemented. But if you insist not to use that style of coding, here is an alternative version.
bool done = false;
while (expression1 && !done)
{
while (expression2 && !done)
{
// do something
done = true;
}
}
// execution will jump here.
It introduces a new control variable, done. The expression && !done must be added to every loop. In addition, there must be no reachable code after the breaking statement done = false;.
What do you think? Which is more convenient to use?
Enjoyed this article? Subscribe to our RSS feed for free!