Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Choosing with if and else
    4. if with an initializer
    5. Picking one of many with switch
    6. Forgetting break
    7. Repeating with while and do/while
    8. Counting with for
    9. Range-based for
    10. Leaving early: break and continue
    11. Loops inside loops
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. = instead of ==
    16. Reading one past the end
    17. Try it yourself

    Module 1 · Basics

    1.4Control flow

    Make decisions with if and switch, and repeat work with while, do/while, for and range-based for. Learn when to use each, how break and continue change a loop, and the off-by-one and fall-through mistakes the tools catch for you.

    About 25 minutesBeginner

    On this page
    1. Key terms
    2. In 30 seconds
    3. Choosing with if and else
    4. if with an initializer
    5. Picking one of many with switch
    6. Forgetting break
    7. Repeating with while and do/while
    8. Counting with for
    9. Range-based for
    10. Leaving early: break and continue
    11. Loops inside loops
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. = instead of ==
    16. Reading one past the end
    17. Try it yourself

    Key terms

    condition
    An expression that is true or false, like quality >= 30, that decides what runs next.
    block
    Statements between { and }. Variables declared inside a block exist only until its }.
    if with an initializer
    if (init; condition) declares a variable that exists only inside the if and its else.
    switch and case
    switch (x) jumps to the case label that matches x, or to default if none does.
    fall through
    When a case has no break, running continues into the next case.
    [[fallthrough]]
    An attribute, a note to the compiler, that says falling into the next case is on purpose.
    loop
    Code that runs its body again and again while a condition holds. Each run is one iteration.
    while and do/while
    while checks its condition before each iteration; do/while checks it after, so the body runs at least once.
    for
    A loop with three parts in one line: a start, a condition and a step, like for (int i = 0; i < 3; ++i).
    range-based for
    for (char base : dna) visits each element of a string or container in order.
    break and continue
    break leaves the innermost loop or switch at once; continue skips to the next iteration.
    nested loop
    A loop inside another loop. The inner loop runs all the way through for each step of the outer one.
    off-by-one error
    A loop that runs one time too many or too few, often by writing <= where < was meant.

    A program that runs every line once, top to bottom, can’t do much. Real programs choose: a read with low quality is skipped, an unknown base is reported. And they repeat: the same check runs for every base in a sequence. Control flow is the set of statements that decide which code runs, and how many times.

    In 30 seconds

    • if/else runs one block or another. switch jumps to the case that matches a value, and needs a break at the end of each case.
    • for (int i = 0; i < n; ++i) counts, for (char base : dna) visits every element, while repeats until a condition changes, and do/while runs at least once.
    • break leaves a loop early; continue skips to the next iteration.
    • Writing <= instead of < reads past the end, and a case without break runs into the next one. The tools catch both.

    Choosing with if and else

    if (condition) runs the block after it only when the condition is true. else gives a block for when it’s false, and else if adds more conditions, checked in order. The first true one wins.

    #include <print>
    
    int quality = 25;
    if (quality >= 30) {
        std::println("high");
    } else if (quality >= 20) {
        std::println("usable");
    } else {
        std::println("low");
    }

    Output

    usable

    Always write the braces, even around one line. Without them, only the next statement belongs to the if, and a line added later silently runs every time.

    if with an initializer

    Often you compute a value only to test it. if (init; condition) declares the variable inside the if, so it exists in the if and else blocks and nowhere else:

    #include <print>
    #include <string>
    
    std::string read = "ACGTNACG";
    if (auto pos = read.find('N'); pos != std::string::npos) {
        std::println("unknown base at position {}", pos);
    } else {
        std::println("no unknown bases");
    }

    Output

    unknown base at position 4

    read.find('N') gives the position of the first N, counting from 0, or the special value std::string::npos when there isn’t one. After the if, the name pos is free again, so it can’t be used by mistake.

    Picking one of many with switch

    When you compare one value against a list of constants, switch is clearer than a chain of else if. It jumps to the case label that matches, or to default if none does. break ends the switch. Several labels in a row share the code below them.

    #include <print>
    
    char base = 'G';
    switch (base) {
    case 'A':
    case 'T':
        std::println("weak pair: 2 hydrogen bonds");
        break;
    case 'G':
    case 'C':
        std::println("strong pair: 3 hydrogen bonds");
        break;
    default:
        std::println("not a base");
        break;
    }

    Output

    strong pair: 3 hydrogen bonds

    A switch works on integers, characters and enumerations (Module 4 shows those). It doesn’t work on std::string; use if and == there.

    Forgetting break

    Without break, a case keeps running into the code of the next case. This is called falling through, and it’s almost always a bug. With the course’s flags, both compilers warn about it, and with warnings as errors it doesn’t compile:

    #include <print>
    
    char base = 'A';
    switch (base) {
    case 'A':
        std::println("adenine");
    case 'C':
        std::println("cytosine");
        break;
    default:
        std::println("something else");
        break;
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:6:17: error: this statement may fall through [-Werror=implicit-fallthrough=]
        6 |     std::println("adenine");
          |     ~~~~~~~~~~~~^~~~~~~~~~~
    main.cpp:7:1: note: here
        7 | case 'C':
          | ^~~~
    cc1plus: all warnings being treated as errors

    The fix is to add break; after std::println("adenine");. When falling through is what you want, say so with [[fallthrough]]; as the last statement of the case. Here each verbosity level prints its own messages plus those of every level below it:

    #include <print>
    
    int level = 2;
    switch (level) {
    case 2:
        std::println("show details");
        [[fallthrough]];
    case 1:
        std::println("show warnings");
        [[fallthrough]];
    case 0:
        std::println("show errors");
        break;
    default:
        std::println("unknown level");
        break;
    }

    Output

    show details
    show warnings
    show errors

    Common pitfallWhy the flags include -Wimplicit-fallthrough

    GCC catches a missing break with -Wextra, but Clang needs -Wimplicit-fallthrough spelled out. That’s why the flags from Setting up name it: with them, both compilers stop every fall-through you didn’t mark.

    Repeating with while and do/while

    while (condition) checks the condition, runs the body if it’s true, and repeats. Use it when you don’t know in advance how many times the loop will run. Here a cell culture doubles every generation; how many generations until it has at least 1000 cells?

    #include <print>
    
    int cells = 1;
    int generations = 0;
    while (cells < 1000) {
        cells *= 2;
        ++generations;
    }
    std::println("{} generations, {} cells", generations, cells);

    Output

    10 generations, 1024 cells

    A while loop might not run at all, if the condition is false from the start. do { ... } while (condition); checks after the body instead, so the body always runs at least once. Counting the digits of a number needs that: even 0 has one digit.

    #include <print>
    
    int value = 0;
    int digits = 0;
    do {
        ++digits;
        value /= 10;
    } while (value != 0);
    std::println("{} digit", digits);

    Output

    1 digit

    With a plain while (value != 0), the body would never run and the answer would be 0 digits.

    Counting with for

    A for loop puts the three parts of a counting loop on one line: a start that runs once, a condition checked before each iteration, and a step that runs after each one.

    #include <print>
    
    for (int i = 1; i <= 3; ++i) {
        std::println("{} squared is {}", i, i * i);
    }

    Output

    1 squared is 1
    2 squared is 4
    3 squared is 9

    A variable declared in the start, like i, belongs to the loop. It no longer exists after the loop ends:

    #include <print>
    
    for (int i = 0; i < 3; ++i) {
        std::println("{}", i);
    }
    std::println("{}", i);

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:6:20: error: ‘i’ was not declared in this scope
        6 | std::println("{}", i);
          |                    ^

    If you need the value after the loop, declare the variable before the for.

    Range-based for

    To visit every element of a string or container in order, you don’t need a counter at all. for (char base : dna) runs the body once for each character, with base holding it:

    #include <print>
    #include <string>
    
    std::string dna = "GATTACA";
    int gc = 0;
    for (char base : dna) {
        if (base == 'G' || base == 'C') {
            ++gc;
        }
    }
    std::println("{} of {} bases are G or C", gc, dna.size());

    Output

    2 of 7 bases are G or C

    There’s no index to get wrong, so prefer this form whenever you visit everything. The loop variable is a copy of each element, so changing it doesn’t change the string:

    #include <print>
    #include <string>
    
    std::string dna = "gattaca";
    for (char base : dna) {
        base = 'N'; // changes the copy only
    }
    std::println("{}", dna);

    Output

    gattaca

    To change the elements themselves, loop with auto&, which References explains.

    Leaving early: break and continue

    break leaves the loop at once. continue skips the rest of this iteration and moves on to the next one. This loop adds up quality scores from a std::vector (a list of values, which Module 3 covers in full). It skips scores below 20 and stops at -1, which marks the end of the data:

    #include <print>
    #include <vector>
    
    std::vector<int> scores = {38, 12, 40, -1, 35};
    int total = 0;
    for (int score : scores) {
        if (score < 0) {
            break; // end of the data
        }
        if (score < 20) {
            continue; // too low: skip it
        }
        total += score;
    }
    std::println("{}", total);

    Output

    78

    38 and 40 are added; 12 is skipped, and the loop ends before it reaches 35.

    Loops inside loops

    A loop can contain another loop. For each step of the outer loop, the inner loop runs all the way through. That’s how you visit a grid, like the rows and columns of an image. std::print is std::println without the new line, so the numbers of one row stay on one line; std::println() on its own then ends the line. {:3} prints each number 3 characters wide:

    #include <print>
    
    for (int row = 1; row <= 3; ++row) {
        for (int col = 1; col <= 4; ++col) {
            std::print("{:3}", row * col);
        }
        std::println("");
    }

    Output

      1  2  3  4
      2  4  6  8
      3  6  9 12

    break only leaves the innermost loop. To stop both loops, set a bool and check it in the outer condition:

    #include <print>
    
    int target = 6;
    bool found = false;
    for (int row = 1; row <= 3 && !found; ++row) {
        for (int col = 1; col <= 4; ++col) {
            if (row * col == target) {
                std::println("found at row {}, col {}", row, col);
                found = true;
                break;
            }
        }
    }

    Output

    found at row 2, col 3

    Without !found in the outer condition, the search would carry on and also report row 3, col 2. Putting the search in its own function and using return, which Functions covers, is often cleaner.

    Which one should I use?

    WhatWhenWhyHow
    if / elseA yes/no choice, or conditions that aren’t all about one value.Any condition works, including ranges like >= 20.if (quality >= 30) { ... }
    switchOne integer or character compared with a list of constants.Easier to read than a long else if chain, and often faster.switch (base) { case 'A': ... break; }
    Range-based forVisiting every element of a string or container, in order.No index, so no off-by-one errors.for (char base : dna)
    forCounting, or when you need the position of each element.Start, condition and step are all in one line.for (int i = 0; i < n; ++i)
    whileRepeating until something changes, with no count known in advance.It says exactly what it waits for.while (cells < 1000)
    do / whileLike while, but the body must run at least once.The check comes after the body.do { ... } while (value != 0);
    Which loop?
    1. Do you visit every element of a string, vector or array, in order?

      Yes

      Range-based forfor (char base : dna)

      No
    2. Do you count through numbers or positions with a known end?

      Yes

      forfor (int i = 0; i < n; ++i)

      No
    3. Must the body run once before you can check the condition?

      Yes

      do / while

      No
    4. Otherwise: while: repeat until a condition changes

    Rule of thumb: use a range-based for when you can, a counting for when you need the position, and while for everything else. Give every case a break or a [[fallthrough]].

    Under the hood

    A for loop is a while loop with its parts gathered on one line. These two loops do exactly the same thing:

    #include <print>
    
    for (int i = 0; i < 2; ++i) {
        std::println("for {}", i);
    }
    
    int i = 0;
    while (i < 2) {
        std::println("while {}", i);
        ++i;
    }

    Output

    for 0
    for 1
    while 0
    while 1

    The processor knows nothing about if or loops. It runs instructions one after another, and it can jump: to a fixed place, or to a place only if the last comparison came out a certain way. The compiler turns an if into a comparison and a jump over the block, and a loop into a comparison and a jump back to the start.

    A switch over many close values, like the cases 0 to 9, often becomes a jump table: the value is used as an index into a list of addresses, so the right case is found in one step instead of by comparing against each value in turn.

    PerformancePredictable branches are cheap

    A modern CPU guesses which way each jump will go before it knows, and keeps working. A loop condition that is true a thousand times and then false once is almost free. A condition that flips at random, like testing random data, costs much more. Module 9, Performance, measures it.

    Common pitfalls

    = instead of ==

    = assigns and == compares. if (errors = 3) sets errors to 3 and is then always true. Both compilers warn, so it doesn’t compile here:

    #include <print>
    
    int errors = 0;
    if (errors = 3) {
        std::println("found errors");
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:4:12: error: suggest parentheses around assignment used as truth value [-Werror=parentheses]
        4 | if (errors = 3) {
          |     ~~~~~~~^~~
    cc1plus: all warnings being treated as errors

    The fix is if (errors == 3).

    Reading one past the end

    An array of 3 elements has positions 0, 1 and 2. A loop that runs while i <= 3 reads position 3 too, which isn’t there. You met this bug in Setting up: the compiler can’t see it, and UndefinedBehaviorSanitizer catches it when the program runs. This example uses a plain C array, int scores[] = {...}, which Arrays, std::array and std::span covers:

    #include <print>
    
    int scores[] = {7, 9, 4};
    int total = 0;
    for (int i = 0; i <= 3; ++i) {
        total += scores[i];
    }
    std::println("{}", total);

    This fails when it runs

    main.cpp:6:22: runtime error: index 3 out of bounds for type 'int [3]'

    Undefined behaviorReading past the end is undefined behavior

    Without sanitizers, this program may print a wrong total, crash, or seem fine: it reads whatever memory happens to follow the array. Write i < 3, with < and the number of elements. Better still, use a range-based for, for (int score : scores), which can’t go past the end.

    Try it yourself

    Try it yourself

    This program should count how many of each base the read contains, and how many characters are something else. Right now it only counts the total. Use a switch inside the loop to count A, C, G and T separately, and count any other character as unknown.

    #include <print>
    #include <string>
    
    int main() {
        std::string read = "GATTACANNGC";
        int a = 0;
        int c = 0;
        int g = 0;
        int t = 0;
        int unknown = 0;
        int total = 0;
        for (char base : read) {
            ++total;
        }
        std::println("A {} C {} G {} T {} unknown {}", a, c, g, t, unknown);
        std::println("total {}", total);
    }

    Expected output

    A 3 C 2 G 2 T 2 unknown 2
    Show a hint

    Inside the loop, switch on base. Give A, C, G and T each a case that adds 1 to its counter and ends with break, and let default count everything else.

    Show a solution
    #include <print>
    #include <string>
    
    int main() {
        std::string read = "GATTACANNGC";
        int a = 0;
        int c = 0;
        int g = 0;
        int t = 0;
        int unknown = 0;
        for (char base : read) {
            switch (base) {
            case 'A':
                ++a;
                break;
            case 'C':
                ++c;
                break;
            case 'G':
                ++g;
                break;
            case 'T':
                ++t;
                break;
            default:
                ++unknown;
                break;
            }
        }
        std::println("A {} C {} G {} T {} unknown {}", a, c, g, t, unknown);
    }

    The range-based for visits each character once. The switch jumps to the matching case; each case ends with break, so only one counter grows. N matches no case, so it goes to default.

    Saved in this browser only.