TExcelTAD
Home › C › C Switch

C Switch

When one value can match many fixed options — a menu choice, a day number, a command letter — a long chain of else if becomes tedious. The switch statement compares one integer expression against a list of constant cases and jumps straight to the matching one.

Syntax

c
switch (expression) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // code when no case matches
}
  • The expression must be an integer type (int, char, enum, …). Strings and floating-point values are not allowed.
  • Each case label must be a constant known at compile time.
  • break exits the switch.
  • default is optional and runs when nothing else matches.
c · try it yourself
#include <stdio.h>

int main(void) {
    int day = 4;

    switch (day) {
        case 1: printf("Monday\n"); break;
        case 2: printf("Tuesday\n"); break;
        case 3: printf("Wednesday\n"); break;
        case 4: printf("Thursday\n"); break;
        case 5: printf("Friday\n"); break;
        case 6: printf("Saturday\n"); break;
        case 7: printf("Sunday\n"); break;
        default: printf("Not a valid day\n");
    }
    return 0;
}
Thursday

Don't forget break: fall-through

A case label is only an entry point. Once execution enters the switch, it keeps running downward through the following cases until it hits a break (or the end). This is called fall-through:

c · try it yourself
#include <stdio.h>

int main(void) {
    int level = 2;

    switch (level) {
        case 1:
            printf("Level 1 unlocked\n");
        case 2:
            printf("Level 2 unlocked\n");
        case 3:
            printf("Level 3 unlocked\n");
        default:
            printf("(end of list)\n");
    }
    return 0;
}
Level 2 unlocked
Level 3 unlocked
(end of list)

Matching case 2 started execution there, and with no break statements everything below ran too. Usually this is a bug — but it can be useful on purpose.

Grouping cases

Intentional fall-through lets several values share the same code. Stack the labels on top of each other:

c · try it yourself
#include <stdio.h>

int main(void) {
    char letter = 'e';

    switch (letter) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            printf("'%c' is a vowel\n", letter);
            break;
        default:
            printf("'%c' is a consonant\n", letter);
    }
    return 0;
}
'e' is a vowel

A small calculator

switch on a char is a natural fit for operator symbols or menu keys:

c · try it yourself
#include <stdio.h>

int main(void) {
    double a = 12, b = 4;
    char ops[] = {'+', '-', '*', '/', '^'};

    for (int i = 0; i < 5; i++) {
        char op = ops[i];
        switch (op) {
            case '+': printf("%.1f %c %.1f = %.1f\n", a, op, b, a + b); break;
            case '-': printf("%.1f %c %.1f = %.1f\n", a, op, b, a - b); break;
            case '*': printf("%.1f %c %.1f = %.1f\n", a, op, b, a * b); break;
            case '/': printf("%.1f %c %.1f = %.1f\n", a, op, b, a / b); break;
            default:  printf("Unknown operator '%c'\n", op);
        }
    }
    return 0;
}
12.0 + 4.0 = 16.0
12.0 - 4.0 = 8.0
12.0 * 4.0 = 48.0
12.0 / 4.0 = 3.0
Unknown operator '^'

(The for loop simply tries each operator in turn; loops are explained in the next lessons.)

switch vs. if…else

Use switch when… Use if…else when…
comparing one integer/char value against fixed constants testing ranges (score >= 90)
there are many discrete options (menus, commands, states) conditions involve different variables
several values share code comparing strings or floating-point numbers

Declaring variables inside a case

A case label must be followed by a statement, and a declaration is not a statement in C17. Wrap the case body in braces if you need a local variable:

c
switch (cmd) {
    case 1: {
        int temp = compute();
        printf("%d\n", temp);
        break;
    }
}

Tip: Compile with -Wimplicit-fallthrough (included in -Wextra) and GCC warns about cases that fall through without a comment. Mark deliberate fall-through with a /* fall through */ comment.

Test yourself

What happens if a matched case has no break?

  1. The switch exits anyway
  2. Execution continues into the next case
  3. It is a compile error
  4. The default case runs only

Which of these can be used as a switch expression?

  1. A string like "start"
  2. A double
  3. A char
  4. An array

When does the default branch run?

  1. Always, at the end
  2. When no case label matches
  3. When the first case matches
  4. Never — it is just a comment