Learn/C++/4. Making decisions
Lesson 4 of 15
Sign in

C++, lesson 4

Making decisions

Programs become useful when they react differently to different data: a discount for children, a warning for low battery, an error for a wrong password. C++ makes these choices with if and switch.

if, else if, else

The conditions are tested from top to bottom. The first one that is true runs its block and the rest are skipped; else runs when nothing matched. Always use braces, even around a single line, so adding a second line later can't silently change the logic.

Comparison and logical operators

  • == and != test for equal and not equal.
  • <, , and compare order.

2 exercises to try what you just read.

Exercise 1

Cinema ticket

Press Ctrl Enter or Check to test your code.

Exercise 2

Rock, paper, scissors

Press Ctrl Enter or Check to test your code.

<=
>
>=
  • a && b (and) is true when both sides are true.
  • a || b (or) is true when at least one side is true.
  • !a (not) flips true and false.
  • Comparisons produce a bool. && and || short-circuit: the right side is evaluated only if it can still change the answer, so count != 0 && total / count > 5 never divides by zero.

    Beware of = (assignment) where you meant == (comparison). if (x = 5) assigns and is always true; G++ warns about it.

    std::string values compare with the same operators: name == "admin" compares the text, and < compares alphabetically (by character codes, so all uppercase letters sort before lowercase).

    if with an initializer

    C++17 lets you declare a variable inside the if itself. It exists only in the if and its else branches, which keeps helper variables from leaking into the rest of the function:

    The conditional operator

    condition ? a : b picks one of two values. It's great for small choices inside an expression:

    switch

    switch compares one integer, character or enum value against a list of constants:

    Execution jumps to the matching case and continues until break. Without break it "falls through" into the next case. If that's deliberate, write [[fallthrough]]; so the compiler and readers know. switch can't compare strings; use if/else if for those.

    Several cases can share one block:

    Further reading

    • cppreference: if statement
    • cppreference: switch statement
    • cppreference: Comparison operators
    • cppreference: Logical operators

    Read a customer's age and whether they have a student card (y or n). Print the ticket price:

    • under 4: Free
    • 4 to 12: $6
    • 65 or older: $7
    • everyone else: $12, or $9 with a student card

    Read two moves, one per player, each rock, paper or scissors. Rock beats scissors, scissors beats paper, paper beats rock. Print Player 1 wins, Player 2 wins or Draw. If either move is not one of the three words, print Invalid move.

    int battery{14};
    
    if (battery == 0) {
        std::cout << "Shutting down\n";
    } else if (battery < 20) {
        std::cout << "Low battery\n";
    } else {
        std::cout << "OK\n";
    }
    if (int remainder = total % 7; remainder == 0) {
        std::cout << "Even weeks\n";
    } else {
        std::cout << remainder << " extra days\n";
    }
    // remainder no longer exists here
    std::cout << items << (items == 1 ? " item" : " items") << '\n';
    char size{'M'};
    switch (size) {
        case 'S': std::cout << "Small\n"; break;
        case 'M': std::cout << "Medium\n"; break;
        case 'L': std::cout << "Large\n"; break;
        default:  std::cout << "Unknown\n";
    }
    switch (day) {
        case 6:
        case 7:
            std::cout << "Weekend\n";
            break;
        default:
            std::cout << "Weekday\n";
    }
    Input:
    20 y
    Output:
    $9
    Input:
    rock scissors
    Output:
    Player 1 wins