Chapter 10 of 48

Switch Statement

On this page

In Conditional Statements we used else-if ladders to pick one action out of many. That works for anything, but when we are comparing one variable against a list of fixed values (menu option 1, 2, 3; operator '+', '-', '*'; day number 1 to 7), the ladder becomes repetitive:

if (choice == 1)      { ... }
else if (choice == 2) { ... }
else if (choice == 3) { ... }
else                  { ... }

The switch statement is made for exactly this situation. It is shorter, easier to read, and the compiler can often turn it into faster machine code. In this chapter we will learn how switch works, the famous fall-through behavior, which types are allowed, the C++17 additions ([[fallthrough]] and the init-statement), switching on enum class, and the compile errors beginners hit most often.


What is a switch Statement?

A switch statement evaluates an expression once and transfers control to the case label whose constant value equals it. If no label matches, control goes to the default label, or skips the whole switch if there is no default.

The general form is:

switch (expression) {
    case constant1:
        // statements
        break;
    case constant2:
        // statements
        break;
    default:
        // statements when nothing matched
}

The key words here:

  • case label: a "landing point" marked with a constant value.

  • break: leaves the switch immediately and continues after its closing brace.

  • default: the landing point used when no case matches. It is optional.


A First Example

#include <iostream>

int main() {
    int day = 3;

    switch (day) {
        case 1:
            std::cout << "Monday\n";
            break;
        case 2:
            std::cout << "Tuesday\n";
            break;
        case 3:
            std::cout << "Wednesday\n";
            break;
        case 4:
            std::cout << "Thursday\n";
            break;
        case 5:
            std::cout << "Friday\n";
            break;
        default:
            std::cout << "Weekend or invalid day\n";
    }
    std::cout << "After switch\n";
    return 0;
}

Output:

Wednesday
After switch

Step by step:

1. Evaluate day          → 3
2. Find label "case 3:"  → jump there
3. Print "Wednesday"
4. break                 → leave the switch
5. Continue after }      → print "After switch"

The default at the end does not need a break, because nothing comes after it. Many programmers add one anyway, so that the code stays correct if someone later adds another case below it.


Fall-Through: Why break Matters

This is the single most important thing to understand about switch:

A case label is only an entry point. Once execution enters a switch, it keeps running statement after statement, through all the following labels, until it reaches a break (or return, etc.) or the end of the switch. This is called fall-through.

Let's remove the break statements and see what happens:

#include <iostream>

int main() {
    int day = 2;

    switch (day) {
        case 1:
            std::cout << "Monday\n";
        case 2:
            std::cout << "Tuesday\n";
        case 3:
            std::cout << "Wednesday\n";
        default:
            std::cout << "Some other day\n";
    }
    return 0;
}

Output:

Tuesday
Wednesday
Some other day

Control jumped to case 2: correctly, but then simply continued downwards. The labels case 3: and default: are not "checks" that stop anything; they are just positions in the code. With -Wextra, GCC warns about this:

warning: this statement may fall through [-Wimplicit-fallthrough=]

Think of a switch like a building with many doors into one long corridor. The value decides which door you enter, but after that you keep walking until you find an exit (break).

   case 1      case 2      case 3      default
     │           │           │           │
     ▼           ▼           ▼           ▼
 ─────────────────────────────────────────────▶  end of switch
  "Monday"    "Tuesday"  "Wednesday"  "Some other day"
                 ▲
           day == 2 enters here and walks to the end

Grouping Cases: Fall-Through Used on Purpose

Fall-through is not only a source of bugs. When several values need the same action, we can stack labels with no statements between them:

#include <iostream>

int main() {
    char ch = 'E';

    switch (ch) {
        case 'a': case 'e': case 'i': case 'o': case 'u':
        case 'A': case 'E': case 'I': case 'O': case 'U':
            std::cout << ch << " is a vowel\n";
            break;
        default:
            std::cout << ch << " is not a vowel\n";
    }
    return 0;
}

Output:

E is a vowel

Empty labels placed directly one after another do not trigger the fall-through warning; the compiler knows this pattern is intentional.

Worked Example: Grade from Marks

A switch cannot test ranges like marks >= 90 directly, but a small arithmetic trick turns ranges into single values. Integer division by 10 maps 90-99 to 9, 80-89 to 8, and so on:

#include <iostream>

int main() {
    int marks = 86;

    switch (marks / 10) {
        case 10:
        case 9:
            std::cout << "Grade A\n";
            break;
        case 8:
            std::cout << "Grade B\n";
            break;
        case 7:
            std::cout << "Grade C\n";
            break;
        case 6:
        case 5:
        case 4:
            std::cout << "Grade D\n";
            break;
        default:
            std::cout << "Fail\n";
    }
    return 0;
}

Output:

Grade B

86 / 10 is 8 (integer division, from Operators), so control lands on case 8:. The value 100 gives 10, which shares the code of case 9:. This trick only works when the ranges line up with multiples of 10; for uneven ranges (like 0-39, 40-59, 60-74) an else-if ladder is the right tool. Note also that invalid input such as -5 or 150 would land in default and print "Fail", so validate first in a real program.

Intentional Fall-Through with [[fallthrough]] (C++17)

Sometimes one case should do its own work and then continue into the next case. To tell both the compiler and the human reader "this is deliberate", C++17 added the [[fallthrough]] attribute. It must be written as a statement on its own, immediately before the next case or default label.

#include <iostream>

int main() {
    int level = 2;   // 3 = admin, 2 = editor, 1 = viewer

    std::cout << "Permissions:";
    switch (level) {
        case 3:
            std::cout << " delete";
            [[fallthrough]];
        case 2:
            std::cout << " edit";
            [[fallthrough]];
        case 1:
            std::cout << " view";
            break;
        default:
            std::cout << " none";
    }
    std::cout << '\n';
    return 0;
}

Output:

Permissions: edit view

An editor gets everything a viewer gets plus editing; an admin gets everything. The program compiles with -Wall -Wextra without any fall-through warning, because each fall-through is marked.


A Real-World Example: Simple Calculator

A char works nicely as a switch value. Here is the classic menu-driven calculator:

#include <iostream>

int main() {
    double a, b;
    char op;
    std::cout << "Enter expression (e.g. 8 / 2): ";
    std::cin >> a >> op >> b;

    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) {
                std::cout << "Error: division by zero\n";
            } else {
                std::cout << a << " / " << b << " = " << a / b << '\n';
            }
            break;
        default:
            std::cout << "Unknown operator '" << op << "'\n";
    }
    return 0;
}

If the user enters 7.5 * 4:

Enter expression (e.g. 8 / 2): 7.5 * 4
7.5 * 4 = 30

Notice that a case can contain any statements, including a full if-else. Also notice that the switch is on op (a char), not on a or b (which are double); we will see in a moment why switching on a double is not allowed.


Rules of switch

1. The Expression Must Be an Integer or Enumeration Type

The switch expression must have integral type (int, char, bool, short, long, long long, their unsigned versions, ...) or enumeration type, or be a class object that converts to one of these. Small types such as char and short are promoted (integral promotion, from Type Conversion & Casting) before comparison.

Floating-point values and strings are not allowed:

double d = 2.0;
switch (d) { ... }          // error: switch quantity not an integer

std::string cmd = "add";
switch (cmd) { ... }        // error: switch quantity not an integer

Why? Exact equality on floating-point values is unreliable (remember 0.1 + 0.2 != 0.3), and comparing strings is not a single cheap integer comparison. For strings, use an else-if ladder (if (cmd == "add") ... else if (cmd == "sub") ...), or a lookup table such as std::map (see set & map).

2. Case Labels Must Be Constant Expressions

Every case value must be known at compile time: a literal (5, 'A'), a const integer initialised with a constant, a constexpr variable, or an enumerator. An ordinary variable is not allowed:

int k = 2;
constexpr int LIMIT = 3;

switch (x) {
    case LIMIT: break;   // OK: constexpr
    case k:     break;   // error: the value of ‘k’ is not usable in a constant expression
}

3. No Duplicate Case Values

Two labels with the same value make the jump ambiguous, so it is a compile error: duplicate case value. This also catches subtle duplicates like case 'A': and case 65: in ASCII.

4. At Most One default, and It Can Be Anywhere

A switch can have zero or one default. It does not have to be last; the compiler still checks all the cases first and uses default only when none matches. But fall-through still follows the physical order of the code:

#include <iostream>

int main() {
    int x = 9;

    switch (x) {
        default:
            std::cout << "default\n";
        case 1:
            std::cout << "one\n";
            break;
        case 2:
            std::cout << "two\n";
    }
    return 0;
}

Output:

default
one

9 matches no case, so control jumps to default, which is physically first. There is no break, so it falls through into case 1. This kind of code is legal but confusing; in practice, put default last.

5. No Match and No default Means Nothing Happens

If no case matches and there is no default, the entire switch body is skipped. This is not an error.

Summary of Rules

RuleAllowedNot allowed
Switch expression typeint, char, bool, long long, unsigned types, enum, enum classfloat, double, std::string, C strings
Case labelLiteral, constexpr/const integer constant, enumerator, constant expression like 2 * 3Ordinary variables, ranges (case 1-5 means case -4!)
DuplicatesEach value onceSame value twice
defaultZero or one, anywhereTwo default labels

You may see case 1 ... 5: in some code. That is a GCC/Clang extension (case ranges), not standard C++; with -pedantic GCC warns range expressions in switch statements are non-standard. Don't use it in exams or portable code.


Declaring Variables Inside a case

All the cases of a switch share one block (the braces of the switch). This causes a famous compile error:

switch (choice) {
    case 1:
        int total = 10;              // declared in the shared block
        std::cout << total << '\n';
        break;
    case 2:                          // error!
        std::cout << "two\n";
        break;
}

GCC says:

error: jump to case label
note:   crosses initialization of ‘int total’

Why? total's scope extends to the end of the switch block, so it is still "visible" in case 2. But if choice is 2, the jump skips the line that initialises it. C++ forbids jumping past a declaration with an initializer into its scope, because the variable would then exist without ever having been initialised.

The fix is to give the case its own block with braces, so the variable's scope ends before the next label:

#include <iostream>

int main() {
    int choice = 1;

    switch (choice) {
        case 1: {
            int total = 10;          // scope ends at the closing brace
            std::cout << "total = " << total << '\n';
            break;
        }
        case 2: {
            int total = 20;          // a different variable, no clash
            std::cout << "total = " << total << '\n';
            break;
        }
    }
    return 0;
}

Output:

total = 10

Wrapping every non-trivial case in braces is a simple habit that avoids this error forever.


switch with Initializer (C++17)

Just like if (see Conditional Statements), since C++17 a switch can start with an init-statement. The variable lives only inside the switch:

#include <iostream>

int main() {
    int a = 17, b = 5;

    switch (int r = a % b; r) {      // C++17
        case 0:
            std::cout << a << " is divisible by " << b << '\n';
            break;
        default:
            std::cout << "remainder is " << r << '\n';
    }
    // r does not exist here
    return 0;
}

Output:

remainder is 2

switch with enum class

Switches and enumerations are a natural pair: an enum gives readable names to a small fixed set of values, and a switch handles each one. (Enumerations are covered fully in Structures, Unions & Enums; here we only need the basic idea.)

#include <iostream>

enum class Signal { Red, Yellow, Green };

int main() {
    Signal s = Signal::Yellow;

    switch (s) {
        case Signal::Red:
            std::cout << "Stop\n";
            break;
        case Signal::Yellow:
            std::cout << "Get ready\n";
            break;
        case Signal::Green:
            std::cout << "Go\n";
            break;
    }
    return 0;
}

Output:

Get ready

There is a big bonus here. If you switch on an enum, have no default, and forget one of the enumerators, GCC (with -Wall) warns you:

warning: enumeration value ‘Green’ not handled in switch [-Wswitch]

So when you later add a new enumerator such as Signal::Blinking, the compiler points to every switch you forgot to update. A default label silences this warning, which is why many style guides recommend leaving out default when a switch covers an enum completely.

Writing Signal:: before every label is a little noisy. Since C++20, using enum brings the enumerators into scope:

#include <iostream>

enum class Signal { Red, Yellow, Green };

int main() {
    Signal s = Signal::Green;

    switch (s) {
        using enum Signal;           // C++20
        case Red:    std::cout << "Stop\n";      break;
        case Yellow: std::cout << "Get ready\n"; break;
        case Green:  std::cout << "Go\n";        break;
    }
    return 0;
}

Output:

Go

Inside the switch, Red, Yellow and Green can be written without the Signal:: prefix; outside it, the prefix is required again. With -std=c++17 this line is rejected ('using enum' only available with '-std=c++20'). Two more details worth knowing: since there is no default, an enum variable that holds a value with no name (possible through a cast) simply matches no case and the switch does nothing; and a case can also end with return instead of break, because return leaves the whole function and therefore the switch too. You will use that pattern once you write your own functions in Functions.


switch vs else-if Ladder

switchelse-if ladder
TestsEquality with compile-time constants onlyAny condition: ranges, &&, ||, function calls
TypesIntegral and enum typesAnything convertible to bool (doubles, strings, ...)
Evaluates the expressionOncePossibly once per condition
Fall-throughYes, unless you breakNo; at most one branch runs
Typical machine codeJump table (dense values) or binary search (sparse values), chosen by the compilerComparisons one after another, top to bottom
Enum safety-Wswitch warns about missing enumeratorsNo such check

A jump table is an array of code addresses indexed by the switch value, so the jump takes the same time whichever case matches. The standard does not require it; it is an optimisation compilers commonly apply when the case values are close together. For a handful of cases, the speed difference is negligible, so choose based on readability:

One value compared against fixed constants → switch
Ranges, mixed conditions, strings or floating point → if-else

One more difference from Java: C++ (up to C++23) has no switch expression and no arrow-style case -> syntax. A C++ switch is always a statement. To produce a value, assign to a variable in each case or return from a function as in the example above.


Common Mistakes

1. Forgetting break

The most common switch bug. Without break, execution falls into the next case. Compile with -Wextra (or -Wimplicit-fallthrough) so the compiler warns you, and mark real fall-through with [[fallthrough]].

2. Writing a Condition as a Case Label

switch (marks) {
    case marks >= 90:      // error: the value of ‘marks’ is not usable in a constant expression
        ...
}

Case labels are values, not conditions. Use an else-if ladder for ranges, or the / 10 trick when it fits.

3. Writing a Range as a Case Label

case 1-5: is not a range. It is the constant expression 1 - 5, so it means case -4:. It compiles without error and silently does the wrong thing.

4. Switching on a String or double

Both are compile errors (switch quantity not an integer). Use if-else.

5. Declaring an Initialised Variable in a case Without Braces

Gives jump to case label ... crosses initialization. Wrap the case body in { }.

6. Confusing a break in a switch with a break in a loop

A break leaves only the innermost switch or loop. When a switch is inside a loop, break in a case leaves the switch, not the loop. We will look at this carefully in Break & Continue.


Interview / GATE Questions

What is the output of the following code?
int i = 3;
switch (i) {
    case 1: i += 1;
    case 3: i += 3;
    case 5: i += 5;
    default: i += 10;
}
std::cout << i;

Answer: 21. Control enters at case 3 and, with no break, falls through every following label: 3 + 3 = 6, 6 + 5 = 11, 11 + 10 = 21. Note that the switch value is evaluated only once, so changing i inside the switch does not cause another jump.

Can the default label appear before the case labels? What happens then?

Yes. default is still chosen only when no case matches, no matter where it is written. But once control lands there, it falls through into whatever labels come after it, unless there is a break.

Why can't we use double or std::string in a switch?

The standard requires the condition to be of integral or enumeration type (or a class type that converts to one), and every case label to be an integral constant expression. Exact equality of floating-point values is unreliable, and a string comparison is not a single integer comparison, so neither fits the model of jumping to a label chosen by an integer value.

Is case 'A': together with case 65: allowed in one switch?

No, on any system that uses ASCII (or Unicode): 'A' has the value 65, so these are duplicate case values and the program does not compile.

Why does case 1: int x = 5; break; case 2: ... fail to compile, and how do you fix it?

All cases share one block, so x is in scope at case 2, but jumping to case 2 would skip its initialization. C++ forbids jumping over a declaration with an initializer into its scope. Fix: put the case body in braces, case 1: { int x = 5; break; }.

Is a switch always faster than an if-else ladder?

No. The standard says nothing about speed. Compilers often generate a jump table (constant time) for dense case values and a binary search for sparse values, while a naive ladder tests conditions one by one. But an optimising compiler may also turn a simple ladder into the same code as a switch, and for a few cases the difference is negligible. Choose by readability and correctness first.

What does [[fallthrough]] do? Which standard introduced it?

It is a C++17 attribute placed immediately before a case label to say that falling into that label is intentional. It does not change what the program does; it documents the intent and suppresses the compiler's implicit fall-through warning.


In Simple Words

A switch jumps to the case whose constant matches the value, then keeps running until a break. Use it when one integer, char or enum value is compared against fixed constants.

switch (value)                → value must be integral or enum
case CONST:                   → compile-time constant, no duplicates
break;                        → leave the switch (otherwise fall through)
default:                      → runs when nothing matches; optional, at most one
case 1: case 2:               → group values that share code
[[fallthrough]];  (C++17)     → mark intentional fall-through
switch (init; value) (C++17)  → variable scoped to the switch
case X: { int v = ...; }      → use braces when declaring variables
enum + no default             → -Wswitch warns about missing enumerators

So far, our programs make a decision once and then move on. In the next chapter, Loops, we will learn how to repeat a block of code many times, which is where switch-based menus really come to life.