Home Tutorials C Tutorial Switch Statement
Switch Statement

Switch Statement


The switch Statement

What is a switch Statement?

The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of an expression.

It is often used as a cleaner alternative to a long if...else if ladder when you are comparing a single variable against several constant values.

Syntax

switch (expression) {
    case value1:
        // Code to execute
        break;
    case value2:
        // Code to execute
        break;
    default:
        // Code if no cases match
}

Practical Examples

Example 1: Day of the Week

int day = 2;

switch (day) {
    case 1:
        printf("Monday\n");
        break;
    case 2:
        printf("Tuesday\n");
        break;
    case 3:
        printf("Wednesday\n");
        break;
    default:
        printf("Weekend or Invalid Day\n");
}

Example 2: Simple Calculator Logic

char operator = '+';
int a = 10, b = 5;

switch (operator) {
    case '+':
        printf("Result: %d", a + b);
        break;
    case '-':
        printf("Result: %d", a - b);
        break;
    default:
        printf("Error: Invalid Operator");
}
Crucial Rule: Don't forget the break; statement! Without it, the program will continue executing the code in the next case blocks even if they don't match. This is called "falling through."

🏋️ Test Yourself With Exercises

Take our quiz on Switch Statement to test your knowledge.

Browse Quizzes »