Switch Case in C: What Is Switch Case in C and How to Use It

In c, multi-way branching becomes much cleaner when we use a switch case rather than a deeply nested if-else ladders. When explaining what is switch case in c, a switch case in c is a control-flow statement that compares an integer or character expression against a list of cases and executes the corresponding statements. Learning how to use switch case in c properly means remembering that it is necessary to use break to avoid unwanted fallthru, use default to trap unexpected inputs, and that floating-point values or dynamic strings are not allowed as case constants.

Switch Case in C: Syntax, Break, Default & Jump Table Optimization — Technical Overview

In c, multi-way branching becomes much cleaner when we use a switch case rather than a deeply nested if-else ladders. When explaining what is switch case in c, a switch case in c is a control-flow statement that compares an integer or character expression against a list of cases and executes the corresponding statements. Learning how to use switch case in c properly means remembering that it is necessary to use break to avoid unwanted fallthru, use default to trap unexpected inputs, and that floating-point values or dynamic strings are not allowed as case constants.

#include <stdio.h>

int main(void) {
    char op = '+';
    int a = 15, b = 5;
    switch (op) {
        case '+':
            printf("%d + %d = %d\n", a, b, a + b);
            break;
        case '-':
            printf("%d - %d = %d\n", a, b, a - b);
            break;
        default:
            printf("Unsupported operator\n");
            break;
    }
    return 0;
}

Runnable C example

#include <stdio.h>

int main(void) {
    char op = '+';
    int a = 15, b = 5;
    switch (op) {
        case '+':
            printf("%d + %d = %d\n", a, b, a + b);
            break;
        case '-':
            printf("%d - %d = %d\n", a, b, a - b);
            break;
        default:
            printf("Unsupported operator\n");
            break;
    }
    return 0;
}

Open example in compiler

Expected Output

15 + 5 = 20