C Switch

The C switch statement selects one of many code blocks based on the value of an integer expression. It is a tidy alternative to a long else if chain when you compare one variable against fixed values.

Switch Syntax

#include <stdio.h>

int main(void) {
    int day = 3;
    switch (day) {
        case 1: printf("Monday\n"); break;
        case 2: printf("Tuesday\n"); break;
        case 3: printf("Wednesday\n"); break;
        default: printf("Another day\n");
    }
    return 0;
}
Wednesday

How the C Switch Statement Works

  • The expression is evaluated once.
  • Its value is compared with each case label, which must be a constant integer or char.
  • break jumps out of the switch; without it, execution falls through to the next case.
  • default runs when no case matches and is optional.

Using Fall-Through on Purpose

Stacking case labels lets several values share the same code.

#include <stdio.h>

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

Switch vs if else in C

Use switch when you test one integer or character against many exact values. Use if else for ranges (score >= 90), floating-point values, strings, or complex conditions, because switch cannot handle those.

Frequently asked questions

What happens if I forget break in a C switch?

Execution continues into the next case and runs its code too, which is called fall-through. This is a frequent bug unless it is intentional.

Can I use strings in a C switch statement?

No. Case labels must be integer constants, including characters and enum values. To compare strings, use if else with strcmp.

Is switch faster than if else?

Compilers can turn a switch into a jump table, which can be faster for many cases, but modern compilers optimize both well. Choose whichever is clearer.