Advertisement

switch Statement

C Language Control Flow 📅 May 2026 ⏱ 1 min read 🆓 Free

switch Statement in C

The switch statement is a cleaner alternative to long if-else chains. It checks one variable against multiple fixed values.

Syntax

c
switch (expression) {
    case value1:
        // code here
        break;       // exit switch
    case value2:
        // code here
        break;
    default:         // runs if no case matches
        // code here
}

Simple Calculator using switch

c
#include <stdio.h>

int main() {
    float a, b;
    char  op;
    
    printf("Enter: number op number (e.g. 10 + 5): ");
    scanf("%f %c %f", &a, &op, &b);
    
    printf("%.2f %c %.2f = ", a, op, b);
    
    switch (op) {
        case '+': printf("%.2f\n", a + b); break;
        case '-': printf("%.2f\n", a - b); break;
        case '*': printf("%.2f\n", a * b); break;
        case '/':
            if (b != 0)  printf("%.2f\n", a / b);
            else         printf("Error: Division by zero!\n");
            break;
        default:
            printf("Unknown operator!\n");
    }
    return 0;
}
▶ Output
Enter: number op number (e.g. 10 + 5): 15 * 4
15.00 * 4.00 = 60.00

switch vs if-else Comparison

Featureswitchif-else
Best forFixed values (int, char only)Ranges, complex conditions
SpeedFaster — uses jump tableSlightly slower — checks sequentially
float allowed?NOYES
ReadableVery clean for many optionsGets messy with 5+ conditions
Fall-throughYes — without breakNo
⚠ Warning: ALWAYS add break; at the end of each case! Without break, execution falls through to the next case automatically — this is usually a bug.
Advertisement
← Back to C Language Index