Thuta Learning
C++
BasicProgrammingBeginner

Switch

C++Lesson 1025 min

What you'll walk away with

  • Write a switch with case labels, break and default, and trace which statements run
  • Spot accidental fall-through and mark intentional fall-through with [[fallthrough]]
  • Group several case labels that share one action
  • Know that switch works on integers, chars and enums but not on std::string or ranges

Explain it simply

Explain it simply

A switch looks at one value and jumps straight to the case label that matches it. It is a tidy way to handle a menu choice, a keyboard command or a status code, where each possible value needs its own action. Think of a lift: you press 3, and the lift goes directly to floor 3 instead of stopping to ask at floors 1 and 2.

Each case ends with break, which leaves the switch. If no label matches, the default label runs, much like the final else of an if chain. The one rule that surprises everyone is that cases are only labels, not walls: without break, execution keeps going into the next case.

Problem → Why → Solution

The problem: one menu choice, two actions

A file manager's menu has three options. Someone adds a new message to option 1 and, while editing, deletes its break line. Now choosing 1 prints Create new file and then Open existing file as well, and the program opens a file the user never asked for. The code compiles, and in a quick test of option 2 everything looks perfect.

menu_bug.cpp
#include <iostream>

int main() {
    int option = 1;

    switch (option) {
        case 1:
            std::cout << "Create new file\n";
            // break is missing here
        case 2:
            std::cout << "Open existing file\n";
            break;
        default:
            std::cout << "Invalid option\n";
    }
    return 0;
}

Why did two cases run?

Case labels are entry points, not separate blocks. switch jumps to the matching label and then runs statements in order until it reaches a break or the closing brace, crossing any other labels on the way. That behaviour, called fall-through, is occasionally useful, so the compiler does not reject it. g++ -Wextra does warn: this statement may fall through [-Wimplicit-fallthrough=]. End every case with break unless you mean to fall through.

Core concept: jump to a label, run until break

switch (expression) evaluates its expression once. The value must have an integral type such as int or char, or an enumeration type; floating-point values and std::string are not allowed, and switching on a std::string fails with switch quantity not an integer. Each case label must be a constant known at compile time, such as 2, 'q' or an enumerator, and no two labels may have the same value.

After evaluating the value, the program jumps directly to the matching case label, or to default if none matches. If there is no default and nothing matches, the whole switch is skipped. From the label it lands on, execution runs straight down through the statements, ignoring further labels, until a break leaves the switch. Several labels can share one body by being stacked: case 'y': case 'Y': followed by one block of statements. Stacked empty labels never trigger a fall-through warning.

When falling from one non-empty case into the next is deliberate, C++17's [[fallthrough]]; statement, placed just before the next label, documents the intent and silences -Wimplicit-fallthrough. It does not change what happens; the code would fall through anyway.

Because all cases share one scope, declaring and initialising a variable directly under a case is an error: jump to case label, crosses initialization of 'int count'. A jump to a later label would skip the initialisation. Wrap the case body in braces to give it its own scope. Finally, switch only tests equality with single values, so for ranges such as mark >= 80, use an if chain.

SituationBetter choice
A menu choice, command letter or status codeswitch
Ranges such as mark >= 80if / else if
Comparing std::string valuesif / else if (or a lookup table)
Every value of an enum must be handleda switch without default, so -Wswitch can warn
Mental model: how a switch runs
  1. Evaluate the value once
  2. Jump to the matching case or default
  3. Run down until break or the end
  4. break leaves the switch

Case labels are doors into one long corridor of code; break is the only exit before the end.

General pattern

cpp
switch (value) {            // int, char or enum
    case CONSTANT_A:
        // statements
        break;
    case CONSTANT_B:
    case CONSTANT_C:        // two labels share one action
        // statements
        break;
    default:
        // no label matched
}

The value must be of integral or enum type, and every label must be a compile-time constant. Close each case with break; stacked labels share one action, and default catches every other value.

Example: a three-option menu

The menu below maps the numbers 1, 2 and 3 to actions and sends anything else to default. option is 2, so trace the jump and the exit before reading the breakdown, then imagine what would print for 7.

cpp
#include <iostream>
using namespace std;

int main() {
    int option = 2;

    switch (option) {
        case 1:
            cout << "Create new file";
            break;
        case 2:
            cout << "Open existing file";
            break;
        case 3:
            cout << "Exit program";
            break;
        default:
            cout << "Invalid option";
    }
    return 0;
}

Code breakdown

  1. The tested valueswitch (option) {

    option is evaluated once, giving 2. Because it is an int it can be switched on, and the program now jumps straight to the label with value 2.

  2. The matching casecase 2:

    The jump lands here. case 1 is skipped entirely; its statements are never even looked at.

  3. The actioncout << "Open existing file";

    This is the only line of output. Nothing sends a newline at the end, so the terminal prompt may appear right after the text.

  4. Leaving the switchbreak;

    Each case ends with break, so after printing, control jumps to the line after the switch's closing brace. Delete the break under case 2 and the program would print Exit program right after it.

  5. Fallbackdefault:

    Runs for any option other than 1, 2 or 3, such as 7 or -1. The last label needs no break because the switch ends right after it, though many style guides add one anyway for safety.

You should see
Open existing file
Where the switch jumps
  1. Evaluate option
  2. Jump to case 2
  3. Print the message
  4. break: leave the switch

option is 1, 2 or 3

matching case

any other value

default

Intentional fall-through with [[fallthrough]]

Fall-through has one classic legitimate use: cumulative levels, where a higher level gets everything a lower level gets, plus more. Below, an admin receives delete, edit and view rights, while a viewer only gets view. [[fallthrough]]; tells both the compiler and the next reader that the missing break is on purpose.

permissions.cpp
#include <iostream>

int main() {
    char role = 'e';   // 'a' = admin, 'e' = editor, 'v' = viewer

    std::cout << "Permissions:";
    switch (role) {
        case 'a':
            std::cout << " delete";
            [[fallthrough]];
        case 'e':
            std::cout << " edit";
            [[fallthrough]];
        case 'v':
            std::cout << " view";
            break;
        default:
            std::cout << " none";
    }
    std::cout << '\n';
    return 0;
}

role is 'e', so the switch jumps to case 'e', prints edit, falls into case 'v', prints view, and break leaves. The output is Permissions: edit view.

Switching on an enum class

Magic numbers such as 1, 2 and 3 say nothing about their meaning. An enum class gives each value a name, and a switch over it reads like a specification. Leave out default when you mean to handle every enumerator: if someone later adds a value such as Refunded, g++ -Wall reports enumeration value 'Refunded' not handled in switch [-Wswitch], pointing you to every switch that needs updating.

order_status.cpp
#include <iostream>

enum class OrderStatus { Pending, Shipped, Delivered };

int main() {
    OrderStatus status = OrderStatus::Shipped;

    switch (status) {
        case OrderStatus::Pending:
            std::cout << "Waiting for payment\n";
            break;
        case OrderStatus::Shipped:
            std::cout << "On the way\n";
            break;
        case OrderStatus::Delivered:
            std::cout << "Delivered\n";
            break;
    }
    return 0;
}

C++20: using enum inside the switch

In C++20 you can write using enum OrderStatus; at the top of the switch body and then shorten the labels to case Pending: instead of OrderStatus::Pending. Type safety stays exactly the same.

In real projects

Where this shows up in real projects

Command-line tools parse single-letter options with a switch on a char: -v for verbose, -o for output, -h for help, with default printing a usage message. Interpreters and emulators are built around one large switch on an instruction code, and network code handles protocol message types the same way. In each of these, every possible value has a distinct, fixed meaning, which is exactly what switch is for.

State machines are the other big user. A game character, a traffic light or an order in a shop moves between a fixed set of states, usually stored as an enum class, and a switch decides what happens in each state. Teams rely on -Wswitch (a switch without default) so that adding a new state turns every switch that forgot it into a compiler warning, and many build with -Werror in CI so that the warning blocks the merge.

Common mistakes

Common mistakes

1. Forgetting break

Without break, the matching case runs and then every case below it until the next break. g++ -Wextra warns with this statement may fall through [-Wimplicit-fallthrough=]. Add break, or [[fallthrough]]; when the fall-through is intentional.

2. Declaring a variable directly under a case

case 3: int count = 0; makes the next label fail with jump to case label and crosses initialization of 'int count'. Put the case body in braces: case 3: { int count = 0; ... break; }.

3. Trying to switch on a string or a range

switch (command) on a std::string fails with switch quantity not an integer, and case labels cannot express mark >= 80 at all. Use an if / else if chain for strings and ranges, or map the input to an enum first and switch on that.

Best practices

Best practices

  • End every non-empty case with break, and mark deliberate fall-through with [[fallthrough]].
  • Use enum class values instead of magic numbers for case labels.
  • Include default for input from users or files; omit it in enum switches that must handle every enumerator, so -Wswitch can help.
  • Keep each case short and move long actions into functions, so the switch reads like a table.

Mini challenge

Mini challenge: pocket calculator

Build the core of a calculator that applies one operator character to two numbers.

  • Switch on a char op and support +, -, * and /
  • Accept both '*' and 'x' for multiplication by stacking two case labels
  • In the '/' case, wrap the case body in braces and refuse to divide by zero
  • Print Unknown operator: followed by the character for anything else
calculator.cpp
#include <iostream>

int main() {
    double a = 6.0;
    double b = 4.0;
    char op = 'x';

    // TODO: switch on op
    // TODO: cases for '+' and '-', then '*' and 'x' sharing one action
    // TODO: a '/' case in braces that checks b == 0.0 first
    // TODO: default prints "Unknown operator: " and the character
    return 0;
}

Expected: With op = 'x' the output is: 6 * 4 = 24 With op = '/' it prints 6 / 4 = 1.5, with b = 0.0 it prints Cannot divide by zero, and with op = '%' it prints Unknown operator: %.

Show hint

Stacked labels need nothing between them: case '*': case 'x': followed by one shared block. Inside braces you may declare a variable such as double result. A break inside the if still leaves the whole switch.

Show solution
calculator.cpp
#include <iostream>

int main() {
    double a = 6.0;
    double b = 4.0;
    char op = 'x';

    switch (op) {
        case '+':
            std::cout << a << " + " << b << " = " << a + b << '\n';
            break;
        case '-':
            std::cout << a << " - " << b << " = " << a - b << '\n';
            break;
        case '*':
        case 'x':
            std::cout << a << " * " << b << " = " << a * b << '\n';
            break;
        case '/': {
            if (b == 0.0) {
                std::cout << "Cannot divide by zero\n";
                break;
            }
            double result = a / b;
            std::cout << a << " / " << b << " = " << result << '\n';
            break;
        }
        default:
            std::cout << "Unknown operator: " << op << '\n';
    }
    return 0;
}

Quick quiz 1 / 3

What does this print? int n = 2; switch (n) { case 1: std::cout << "A"; case 2: std::cout << "B"; case 3: std::cout << "C"; break; default: std::cout << "D"; }

Quick quiz 2 / 3

Which of these cannot be used as the value of a switch?

Quick quiz 3 / 3

What does [[fallthrough]]; do?

What to remember

  • switch evaluates one integral or enum value and jumps to the matching case label, or to default.
  • Execution runs down from that label until a break, so a missing break falls into the next case.
  • Stack labels to share an action, and mark deliberate fall-through with [[fallthrough]];.
  • Wrap a case body in braces when it declares variables.
  • Use if / else if for ranges and strings, and an enum class switch without default so -Wswitch can catch missing cases.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Switch | Thuta Learning