CodeBlanks Logo Icon CodeBlanks

The switch statement

Learn multi-way selection with switch, case, break and default.

The switch statement

switch picks one of several cases based on the value of an expression. Each case starts with case and ends with break. If none matches, default runs.

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("Unknown\n");
}

switch only works with integer or char values; it cannot use strings. Each case is a label; when a match is found, flow starts there.

Fall-through behavior

Without break, flow falls through to the next case. Sometimes this is wanted; usually it's a bug.

int n = 1;
switch (n) {
    case 1:
    case 2:
    case 3:
        printf("1-3 range\n");
        break;
    default:
        printf("Outside\n");
}

Here case 1, case 2 and case 3 share the same block. For n=1, n=2 and n=3 you get the same output.

Practice Print the season with switch

Write a C program. Declare int month = 4;. Use switch (month) to print the season: for case 12, case 1, case 2 print printf("Winter\n"); break;, for case 3, case 4, case 5 print printf("Spring\n"); break;, for default print printf("Other\n");. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Declare month, print season with switch
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int month = 4;
    switch (month) {
        case 12: case 1: case 2:
            printf("Winter\n");
            break;
        case 3: case 4: case 5:
            printf("Spring\n");
            break;
        default:
            printf("Other\n");
    }
    return 0;
}

Expected output

Spring

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the switch parts

Term Meaning
switch Main statement
case Case label
break Stop
default Fallback

2 What does break do in a switch?

main.c
case 1: printf("A"); break;
  • Goes to the default case
  • Starts a new case
  • Exits the switch block Correct answer
  • Nothing

Explanation: break exits the switch block.

3 Close the switch

Question
switch (n) {
    case 1: printf("A"); break;
    default: printf("Unknown");
____;
Answer
switch (n) {
    case 1: printf("A"); break;
    default: printf("Unknown");
};

Explanation: The switch block closes with }.

All lessons in Beginner