Loop control statements are used to change the flow of execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. The break
and continue
are loop control statements.
The break
statement terminates a loop without any further consideration.
https://codeeval.dev/gist/90ff553ec6452bf11b20360e065858e0
The continue
statement does not immediately exit the loop, but rather skips the rest of the loop body and goes to the top of the loop (including checking the condition).
https://codeeval.dev/gist/cb46da4aa9b83d6433c71476ce1bbea0
Because such control flow changes are sometimes difficult for humans to easily understand, break
and continue
are used sparingly. More straightforward implementation are usually easier to read and understand. For example, the first for
loop with the break
above might be rewritten as:
for (int i = 0; i < 4; i++)
{
std::cout << i << '\\n';
}
The second example with continue
might be rewritten as:
for (int i = 0; i < 6; i++)
{
if (i % 2 != 0) {
std::cout << i << " is an odd number\\n";
}
}