Namespaces
Variants
Actions

Flow control with break and continue

From cppreference.com


Sometimes it is necessary to exit a loop before the loop condition is met. This is easily done with the break keyword:

for ( /* loop range */ ) {
    ...
    if ( /* condition */ ) {
        break;
    }
    ...
}

The loop is then left immediately, processing continues after the end of the for loop.


Another method of flow control allows to directly start the next iteration of a loop:

for ( /* loop range */ ) {
    ...
    if ( /* condition */ ) {
        continue;
    }
    ...
}

In this case, the loop condition is checked and, if the condition still holds true, the next loop iteration takes place.

See the following example of a very simple prime number generator:

#include <iostream>
 
int main()
{
    for (int x = 2; x < 21; ++x) {
        bool  is_prime = true;
        for (int y = 2; y < x; ++y) {
            if (x % y == 0)
            {
                is_prime = false;
                break;
             }
        }
 
        if (!is_prime)
        {
            continue;
        }
 
        std::cout << x << " is prime" << std::endl;
    }
    return 0;
}

Output:

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime