Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 135 Β· Control Flow

switch Statements

Learn C's switch statement: case labels, break and fall-through, C23 [[fallthrough]], default, switching on enums with -Wswitch, and when if-else is better.

A lot of decisions compare one value against a list of fixed possibilities: which menu option did the user pick, which command letter was typed, which state is the machine in, which day of the week is it? You can write these as a long else if chain, but C has a statement made for exactly this job: switch. It states the question once, lists the answers as case labels, and lets the compiler turn the whole thing into a fast jump table.

switch also has a famous quirk. Once execution enters a case, it doesn't stop at the next label; it keeps going unless you tell it to stop with break. That "fall-through" behavior is occasionally useful and frequently a bug. In this lesson you'll learn how switch really works, how to use break and default, how to mark intentional fall-through in C23, and how switch and enums catch mistakes for you.

The basic switch

C
switch (expression) {
case constant_1:
    // statements
    break;
case constant_2:
    // statements
    break;
default:
    // statements when nothing matched
    break;
}

C evaluates the expression in parentheses once, then jumps to the case label with the matching value. If no label matches, it jumps to default; if there's no default either, the whole body is skipped. break leaves the switch and continues after its closing brace.

C A menu with switch

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Try other numbers in the Input box, including one that isn't on the menu. The break after default isn't strictly needed when default comes last, but writing it anyway means nothing breaks if someone later adds a case below it.

Styles differ on indentation: some code indents case labels one level inside the switch, some (like the Linux kernel and this course) lines them up with switch. Both are fine; be consistent.

What you can switch on

The controlling expression must have an integer type: int, char, long, unsigned, an enum type, bool and so on. Each case label must be an integer constant expression, a value the compiler knows at compile time:

  • Literals: case 42:, case 'q':, case -1:
  • Enumeration constants: case RED:
  • Constant arithmetic: case 'a' + 1: or case 1 << 3:
  • Macros that expand to constants: case MAX_LEVEL:
  • In C23, constexpr variables: constexpr int limit = 10; then case limit:

What you can't use:

  • Strings. switch (command) with case "quit": doesn't compile, because strings aren't integers. Use an if/else if chain with strcmp (see String Functions), or switch on the first character when that's enough.
  • Floating-point values. switch (price) with a double is an error.
  • Ranges. case 1 to 5 doesn't exist in standard C. GCC and Clang support case 1 ... 5: as an extension, but it isn't portable; list the values or use if.
  • Duplicate labels, which are a compile error.
  • Variables. Even a const int isn't an integer constant expression in standard C. Recent GCC versions accept one as an extension, but other compilers reject it; use an enum constant, a #define or a C23 constexpr instead (see Constants).

break and fall-through

The labels in a switch are only entry points. After jumping to a matching case, execution runs straight through any following labels until it reaches a break, a return, or the end of the switch. Forgetting a break is one of the classic C bugs:

C A missing break falls through

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first switch jumps to case 2 and then prints "medium", "hard" and "unknown". The example compiles with warnings on purpose: -Wextra turns on -Wimplicit-fallthrough, and GCC reports this statement may fall through for each case that runs into the next one.

Grouping cases

Fall-through is useful when several values share the same code. Labels with no statements between them are the standard idiom, and compilers never warn about them:

C Several case labels sharing one branch

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

For character classes like these, the <ctype.h> functions (isdigit, isalpha, isspace) are usually shorter; see Characters and ASCII. The point here is the shape: many labels, one body.

Marking intentional fall-through in C23

Sometimes a case should do its own work and then continue into the next one. C23 adds a standard attribute for that, [[fallthrough]];, placed right before the next label. It tells both the compiler and the reader that the missing break is deliberate, and it silences the warning. Before C23, people wrote a comment such as /* fall through */, which GCC also recognizes; GCC and Clang also accept __attribute__((fallthrough)); as an extension.

C Intentional fall-through with [[fallthrough]]

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

This compiles without a single warning, and the intent is obvious to anyone reading it. Use fall-through sparingly; when the shared work grows, a helper function called from each case is usually clearer.

default

default handles every value without its own case. It can appear anywhere in the switch, though putting it last is the convention. Even when you believe every possible value is covered, a default that reports the unexpected value can save hours of debugging when the impossible happens anyway, for example after a corrupted file or a new value added elsewhere in the program.

Switching on enums

switch and enumerations are natural partners. An enum gives names to a fixed set of states, and a switch handles each one. GCC adds a safety net: with -Wall, if you switch on an enum type without a default and forget one of its constants, you get enumeration value 'X' not handled in switch. When you add a new constant to the enum later, every switch that needs updating lights up.

C A traffic light state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Here each case uses return, which leaves the function and therefore the switch, so no break is needed. Leaving out default is deliberate: it keeps the -Wswitch check active. The return after each switch handles out-of-range values (C doesn't stop you from storing 7 in an enum light) and keeps the compiler from warning that control can reach the end of a non-void function.

Declarations inside a switch

A case label is just a label, and the whole switch body is one block. Two consequences:

  • A variable declared after one case is still in scope in the following cases, but its initialization only runs if execution passes through it. Jumping to a later case skips the initializer, leaving the variable with an indeterminate value.
  • Before C23, a label couldn't be followed directly by a declaration at all, so case 1: int x = 5; was a compile error. C23 allows it, but the scope problem remains.

The clean solution is to give the case its own block:

C
switch (command) {
case 'a': {
    int amount = read_amount();   // scoped to this case only
    add(amount);
    break;
}
case 'r':
    reset();
    break;
}

switch or if-else?

Use switch when… Use if/else if when…
one integer or enum value is compared with many constants conditions test different variables
several values share a branch you need ranges (score >= 90)
you want -Wswitch to check enum coverage you compare strings or floating-point values
a menu, command letter or state machine there are only two or three cases

For dense case values, compilers often build a jump table, which finds the right case in constant time instead of testing values one by one. With modern optimizers an else if chain over constants can end up just as fast, so choose whichever form reads better.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does this print? int n = 2; switch (n) { case 1: printf("a"); case 2: printf("b"); case 3: printf("c"); break; default: printf("d"); }

    Execution jumps to case 2, prints b, falls through into case 3, prints c, and then break leaves the switch before default.
  2. 2. Which of these can be used as a case label in standard C?

    Case labels must be integer constant expressions, and a character constant like 'y' is an integer. Strings and floating-point values are not allowed, and ranges with ... are a GCC/Clang extension.
  3. 3. What does [[fallthrough]]; do in C23?

    The attribute documents that the missing break is intentional. Without it, -Wimplicit-fallthrough (part of -Wextra) warns.
  4. 4. With enum color { RED, GREEN, BLUE };, what does GCC with -Wall report for switch (c) { case RED: ...; break; case GREEN: ...; break; } when c is an enum color?

    -Wswitch, part of -Wall, checks that a switch on an enum without a default handles every constant. Adding a default turns the check off.
  5. 5. Why can't you write switch (name) { case "admin": ... } with a char *name?

    Compare strings with strcmp in an if-else chain, or switch on a single character when that is enough.

Summary

  • switch evaluates an integer expression once and jumps to the matching case label, or to default if none matches.
  • Case labels must be distinct integer constant expressions: literals, character constants, enum constants, macros, and C23 constexpr values. No strings, floats or standard ranges.
  • Without break (or return), execution falls through into the next case. -Wextra warns about it; stacked labels with no code between them are the normal way to share a branch.
  • Mark deliberate fall-through with C23's [[fallthrough]];.
  • Switch on enums without default to get -Wswitch coverage warnings, and handle out-of-range values after the switch.
  • Wrap declarations inside a case in their own braces.
  • Prefer switch for one value against many constants; prefer if for ranges, strings and unrelated conditions.

Next: while and do-while Loops