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.
for (int i = 0; i < 10; i++)
{
if (i == 4)
break; // this will immediately exit our loop
std::cout << i << '\n';
}
The above code will print out:
1
2
3
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).
for (int i = 0; i < 6; i++)
{
if (i % 2 == 0) // evaluates to true if i is even
continue; // this will immediately go back to the start of the loop
/* the next line will only be reached if the above "continue" statement
does not execute */
std::cout << i << " is an odd number\n";
}
The above code will print out:
1 is an odd number
3 is an odd number
5 is an odd number
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";
}
}