continue and break

continue and break#

Sometimes we want to exit a loop early or skip the remainder of the loop block if some conditions is met. This is where continue and break come into play.

It is not uncommon to write an infinite loop, like:

for (;;) {
    // do stuff
}

or

while (true) {
    // do stuff
}

In this case, we will want a way to bail out. Here’s an (silly) example of asking for a word from a user and telling them how many letters it contains. But if they enter “0”, we exit:

Listing 38 infinite_loop.cpp#
#include <iostream>
#include <string>

int main() {

    std::string word{};

    while (true) {

        std::cout << "Enter a word (0 to exit): ";
        std::cin >> word;

        if (word == "0") {
            break;
        }

        std::cout << word << " has " << word.size() << " characters" << std::endl;
    }

}

continue is used to skip to the next iteration. Here’s an example that loops over elements of a vector but only operates on them if they are even numbers, in which case, it negates them.

Listing 39 continue_example.cpp#
#include <iostream>
#include <vector>

int main() {

    std::vector<int> a{0, 4, 10, 3, 21, 100, 63, 7, 2, 1, 9, 20};

    for (auto &e : a) {
        if (e % 2 == 1) {
            continue;
        }
        e *= -1;
    }

    for (auto e : a) {
        std::cout << e << " ";
    }
    std::cout << std::endl;
}