Thuta Learning
BasicProgrammingbeginner

Switch

Relax. We'll talk through this in plain words — no textbook voice.

switch lets you run one of several cases based on a single value. For handling fixed values like menu options, day numbers, or command codes, it's often more readable than if...else.

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;
}

option is 2, so case 2 runs. break exits the switch once the matched case is done. default is the fallback that runs when nothing matches any case.

You should see
Open existing file

Info

break — leave it out, and execution can fall through into the next case. That's occasionally intentional, but for beginners it's usually a bug.

Easy traps

  • switch isn't a good fit for range conditions (like mark >= 80). Use switch when you're matching fixed values instead.
Switch | Thuta Learning