break
suggest changeSometimes the loop condition has to be checked in the middle of the body. A break is usually clearer than a flag that skips the rest of the body:
for (;;)
{
// precondition code that can change the value of should_end_loop expression
if (should_end_loop)
break;
// do something
}
Alternative:
bool endLoop = false;
for (; !endLoop;)
{
// precondition code that can set endLoop flag
if (!endLoop)
{
// do something
}
}
break leaves only the innermost loop or switch. To leave an outer loop as well, use a flag, return, or goto.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents