Skip to content
  • The switch Statement · C

The switch Statement

LearnViaNotes @learnvianotes· 2 min read

switch jumps to the case label matching an integer value. Execution falls through into the next case unless you break.

C
#include <stdio.h>

const char *day_type(int day) {
    switch (day) {
        case 0:
        case 6:
            return "weekend";      /* several labels share one body */
        case 1: case 2: case 3: case 4: case 5:
            return "weekday";
        default:
            return "invalid";
    }
}

int main(void) {
    printf("%s %s %s\n", day_type(0), day_type(3), day_type(9));
    return 0;
}
Output
weekend weekday invalid

Fall-through

C
#include <stdio.h>

int main(void) {
    int level = 2;
    switch (level) {
        case 3: printf("gold ");
                /* fall through */
        case 2: printf("silver ");
                /* fall through */
        case 1: printf("bronze ");
                break;
        default: printf("none");
    }
    printf("\n");
    return 0;
}
Output
silver bronze

Rules

  • The controlling expression must have an integer type (int, char, enum…) — not a string or double.

  • case labels must be integer constant expressions and unique. const int variables are not allowed in C; use enum or #define.

  • default is optional and may appear anywhere; it runs when no case matches.

  • Declaring a variable right after a case label needs a block: case 1: { int t = 0; … break; }.

  • For strings, use if/else if with strcmp.

C
#include <stdio.h>

enum Color { RED, GREEN, BLUE };

int main(void) {
    enum Color c = GREEN;
    switch (c) {
        case RED:   printf("stop\n");  break;
        case GREEN: printf("go\n");    break;
        case BLUE:  printf("calm\n");  break;
    }
    return 0;
}
Output
go

switch vs if-else chain — which is faster?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report