Loop Control statements: break and continue
suggest changeLoop 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.
// :glot
#include <iostream>
auto main() -> int
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
break; // this will immediately exit our loop
std::cout << i << '\n';
}
}
0
1
2
3
The continue statement does not leave the loop. It skips the rest of the loop body. In a for loop it then runs the iteration expression and checks the condition. In a while or do loop it goes straight to the condition.
// :glot
#include <iostream>
auto main() -> int
{
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";
}
}
1 is an odd number
3 is an odd number
5 is an odd number
Because such control flow changes are sometimes difficult to follow, break and continue are used sparingly. More straightforward implementations 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";
}
}