Skip to main content
Browse topics

Switch Statement in C

2 min read Updated May 29, 2025
Share

About this page

This is a tutorial in C Controlsswitch, case, break, and fall-through behaviour. For runnable examples, see Switch Case Example Program and Weekdays Switch Program.

Introduction

The switch statement selects one of many code branches based on the value of an integer expression. It is cleaner than a long if-else-if chain when comparing one variable against many constant values.

Syntax

c
switch (expression) {
    case constant1:
        /* statements */
        break;
    case constant2:
        /* statements */
        break;
    default:
        /* optional — runs if no case matches */
        break;
}

Example — Weekday Name

c
#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;
        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("Invalid day\n");
    }

    return 0;
}

Sample Output

plaintext
Wednesday

The break Statement

break exits the switch immediately. Without it, execution falls through to the next case:

c
switch (ch) {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        printf("Vowel\n");
        break;
    default:
        printf("Consonant or other\n");
}

Fall-through is intentional here — multiple cases share one block.

switch vs if-else-if

Use switch whenUse if-else when
Testing one variable against constantsComparing ranges (score >= 80)
Many discrete values (menu options, days)Complex boolean conditions
Integer or char typeAny expression

Best Practices

Common Mistakes

See Switch Case Example Program and Weekdays Switch Program.

Frequently Asked Questions

What types can switch test in C?
switch works with integer types: int, char, short, long, and enum. It cannot test float, double, or strings directly.
Why is break required in switch?
Without break, execution falls through to the next case. break exits the switch after a matching case runs.

Related tutorials

Search tutorials