← Back to all posts

04 C++ Notes

Flow Control

C++ Notes


If / Else

C++
if (condition1) {
    // executes if condition1 is true
}
else if (condition2) {
    // executes if condition1 is false and condition2 is true
}
else {
    // executes if all above conditions are false
}

Switch

C++
switch (x) {
    case 1:
        // code
        break;
    case 2:
        // code
        break;
    case 3:
        // code
        break;
    default:
        // runs if no case matches
        break;
}

Multiple Cases, One Block

C++
case 1:
case 2:
case 3: {
    // executes for case 1, 2, or 3
}
    break;

The fall-through here is intentional. Cases 1, 2, and 3 all fall into the same block because none of them have a break before it, they just stack right into the shared code.


Ternary Expression

C++
result = condition ? option1 : option2;

// if condition is true  -> expression evaluates to option1
// if condition is false -> expression evaluates to option2

Always wrap ternary expressions in parentheses () when using them inside cout. Without them, the << operator may get parsed before ? and cause unexpected behavior.


Code Example: main.cpp

C++
#include <iostream>

int main() {
    int a{10}, b{20}, c{30}, d{40};

    // largest of 3: check a vs b first, then winner vs c
    std::cout << "Largest of 3: "
              << (a>b ? (a>c ? a : c) : (b>c ? b : c))
              << '\n'; // prints: 30

    // largest of 4: same idea extended one level deeper
    std::cout << "Largest of 4: "
              << (a>b ? (a>c ? (a>d ? a : d) : (c>d ? c : d))
                      : (b>c ? (b>d ? b : d) : (c>d ? c : d)))
              << '\n'; // prints: 40

    return 0;
}
Console Output
Largest of 3: 30 Largest of 4: 40

Which One to Reach For

SituationUse
A handful of distinct conditions, possibly ranges or compound logicif / else if / else
One variable checked against many exact, discrete values (int, char, enum)switch
Picking between exactly two values to use immediately, in an assignment or a print statementTernary

Switch only reads clean when the values are genuinely discrete and few. The moment you need a range check like x > 10, switch can't express it at all, that's exactly the signal to reach for if-else instead.


Closing

That covers every branching tool C++ gives you: the flexible one, the discrete-value one, and the compact one. Next up, the three ways to repeat something.

← Previous 03 - Operators and Data Operations Next → 05 - Loops