C/C++ Arena

Step 4 of 7

bool, auto and range-for

A few small upgrades from C that you'll use constantly.

bool

bool is a built-in type with the values true and false. Comparisons produce a bool. When printed with cout it shows as 1 or 0 (or true/false with std::boolalpha).

auto

auto tells the compiler to deduce a variable's type from its initializer: auto n = 5; is an int, auto x = 2.5; is a double. It's especially handy for long type names you'll meet later. The type is still fixed at compile time; auto just saves typing it.

The range-based for loop

This loop visits every element of a string, array or container, without an index:

#include <iostream>
#include <string>

int count_digits(const std::string& s) {
    int n = 0;
    for (char c : s) {
        if (c >= '0' && c <= '9') {
            n++;
        }
    }
    return n;
}

int main() {
    auto label = std::string("room 101, floor 3");
    bool has_digits = count_digits(label) > 0;
    std::cout << count_digits(label) << " " << has_digits << "\n";
    int scores[] = {7, 9, 4};
    int total = 0;
    for (int s : scores) total += s;
    std::cout << total << "\n";
}
4 1
20

Read for (char c : s) as "for each char c in s". On each pass, c is a copy of the next element. You can't accidentally go out of bounds, and there's no off-by-one to get wrong. Use the index form only when you actually need the index.

(const std::string& in the parameter avoids copying the string; the next module explains it.)

Your turn: write int count_vowels(std::string s) that counts a e i o u (lowercase only) using a range-based for loop.

Previous: std::string is easy Next: Namespaces and using