Tutorials / C++: From Basics to Modern C++ / Control flow: if, switch and loops

Control flow: if, switch and loops

14 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. Final project: a command-line expense tracker

Making decisions with if

An if statement runs a block only when a condition is true. The condition is any expression that can be treated as bool.

#include <iostream>

int main() {
    int score{72};

    if (score >= 90) {
        std::cout << "A\n";
    } else if (score >= 70) {
        std::cout << "B\n";
    } else {
        std::cout << "Keep practising\n";
    }
    return 0;
}

The comparison operators are == != < > <= >=. Combine conditions with && (and), || (or) and ! (not). Both && and || short-circuit. In a && b, if a is false then b is never evaluated. You can use this on purpose: if (p != nullptr && p->ready) is safe because the second half only runs when the pointer is valid.

Always use braces, even for a one-line body. Without them, a second line added later silently falls outside the if, and that exact bug has caused real security holes in real products.

if with an initialiser

Since C++17 you can declare a variable inside the if itself. The variable only lives for that statement, which keeps your scope clean.

#include <map>
#include <string>
#include <iostream>

int main() {
    std::map<std::string, int> stock{{"pens", 12}, {"books", 0}};

    if (auto it = stock.find("pens"); it != stock.end()) {
        std::cout << "pens: " << it->second << "\n";
    } else {
        std::cout << "no pens listed\n";
    }
    return 0;
}

Do not worry about std::map yet; we cover it later. The shape of the statement is what matters: if (init; condition).

switch

When you compare one integer or enum value against several constants, switch reads better than a chain of else if.

int day{3};
switch (day) {
    case 1:
        std::cout << "Monday\n";
        break;
    case 2:
        std::cout << "Tuesday\n";
        break;
    case 6:
    case 7:
        std::cout << "Weekend\n";
        break;
    default:
        std::cout << "Midweek\n";
}

Each case needs a break. If you forget it, execution falls through into the next case. Sometimes that is what you want, as in the 6 and 7 pair above, which share one body. When you mean to fall through after doing some work, C++17 lets you write [[fallthrough]]; so the next reader knows it is deliberate. A switch works on integers, characters and enums, but not on strings.

Loops

Use for when you know how many times to repeat, and while when you repeat until something happens.

for (int i = 1; i <= 5; ++i) {
    std::cout << i << " squared is " << i * i << "\n";
}

int n{27};
int steps{0};
while (n != 1) {
    n = (n % 2 == 0) ? n / 2 : 3 * n + 1;   // ternary operator
    ++steps;
}
std::cout << "steps: " << steps << "\n";

The for header has three parts: start, condition, step. I write ++i rather than i++ out of habit. For plain integers there is no difference, but for iterators the prefix form can be cheaper.

The ternary operator cond ? a : b picks one of two values. It is handy in small spots. Nested ternaries are a readability crime, so avoid them.

Range-based for

To visit every element of a container, you do not need an index at all.

#include <vector>
#include <string>

std::vector<std::string> names{"Asha", "Bilal", "Chen"};
for (const std::string& name : names) {
    std::cout << "Hello, " << name << "\n";
}

The const std::string& means "look at each element without copying it". We cover references properly in a later lesson. For now, remember the pattern: const auto& to read, auto& to modify in place, plain auto to copy.

do-while, break and continue

A do-while loop runs the body at least once, then checks the condition. It suits "ask until valid" prompts. break leaves the loop immediately. continue skips to the next iteration.

int guess{};
do {
    std::cout << "Enter a number from 1 to 10: ";
    std::cin >> guess;
} while (guess < 1 || guess > 10);

The common mistake

Writing = where you meant ==. The line if (x = 5) assigns 5 to x and then treats the result as true. It compiles, and the condition is always true. Warnings from -Wall catch it, which is one more reason to leave warnings on. The second classic is an off-by-one error in loops, using <= where < was needed. When you loop over a container by index, the last valid index is size() - 1.

Try it yourself

  1. Write FizzBuzz for 1 to 30: print "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for both, otherwise the number.
  2. Ask the user for a month number and use switch to print how many days it has, ignoring leap years.
  3. Use a do-while loop to keep asking for a password until the user types the right one.
cpp
#include <iostream>

int main() {
    int score{72};

    if (score >= 90) {
        std::cout << "A\n";
    } else if (score >= 70) {
        std::cout << "B\n";
    } else {
        std::cout << "Keep practising\n";
    }
    return 0;
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account