C Switch Statement

Efficient way to handle multiple conditions

🔀 What is a Switch Statement?

Switch statement provides an efficient way to execute different code blocks based on the value of a variable. It's cleaner than multiple if-else statements for many conditions.


// Simple switch example
int day = 3;
switch (day) {
    case 1: printf("Monday"); break;
    case 2: printf("Tuesday"); break;
    case 3: printf("Wednesday"); break;
    default: printf("Other day");
}
                                    

Switch Statement Components

🔍

Switch Expression

Variable or expression to evaluate

switch (variable)
📋

Case Labels

Possible values to match

case value:
🛑

Break Statement

Exit the switch block

break;
🎯

Default Case

Executes when no case matches

default:

🔹 Basic Switch Statement

The switch statement provides an elegant way to handle multiple conditions based on a single variable's value. Unlike multiple if-else chains, switch evaluates an expression once and compares it against different case labels. For example, switch (day) { case 1: printf("Monday"); break; case 2: printf("Tuesday"); break; default: printf("Invalid"); } efficiently matches the day value to corresponding labels. Each case requires a break statement to prevent fall-through behavior. The optional default case handles values that don't match any specified case, making switch statements cleaner and more readable than lengthy if-else ladders for discrete value comparisons.

#include 

int main() {
    int choice = 2;
    
    printf("Menu:\n");
    printf("1. Coffee\n");
    printf("2. Tea\n");
    printf("3. Juice\n");
    printf("Your choice: %d\n", choice);
    
    switch (choice) {
        case 1:
            printf("You ordered Coffee\n");
            printf("Price: $3.00\n");
            break;
        case 2:
            printf("You ordered Tea\n");
            printf("Price: $2.50\n");
            break;
        case 3:
            printf("You ordered Juice\n");
            printf("Price: $4.00\n");
            break;
        default:
            printf("Invalid choice!\n");
            break;
    }
    
    printf("Thank you!\n");
    return 0;
}

Output:

Menu:
1. Coffee
2. Tea
3. Juice
Your choice: 2
You ordered Tea
Price: $2.50
Thank you!

🔹 Switch with Characters

Switch statements work seamlessly with character data types, making them perfect for menu-driven programs and command processing. When using characters in switch cases, enclose them in single quotes like case 'A': or case 'a':. For example, switch (grade) { case 'A': printf("Excellent"); break; case 'B': printf("Good"); break; case 'C': printf("Average"); break; default: printf("Invalid grade"); } processes letter grades efficiently. This approach is commonly used in calculators where operators are characters, text-based menus, and applications requiring single-character commands, providing clear and maintainable code structure for character-based decision making.

#include 

int main() {
    char grade = 'B';
    
    printf("Your grade: %c\n", grade);
    
    switch (grade) {
        case 'A':
        case 'a':
            printf("Excellent! You got 90-100%%\n");
            printf("Keep up the great work!\n");
            break;
        case 'B':
        case 'b':
            printf("Good! You got 80-89%%\n");
            printf("Well done!\n");
            break;
        case 'C':
        case 'c':
            printf("Average. You got 70-79%%\n");
            printf("You can do better!\n");
            break;
        case 'D':
        case 'd':
            printf("Below average. You got 60-69%%\n");
            printf("Need more study!\n");
            break;
        case 'F':
        case 'f':
            printf("Failed. You got below 60%%\n");
            printf("Please retake the exam.\n");
            break;
        default:
            printf("Invalid grade entered!\n");
            break;
    }
    
    return 0;
}

Output:

Your grade: B
Good! You got 80-89%
Well done!

🔹 Fall-through Behavior

Fall-through occurs when you intentionally or accidentally omit break statements in switch cases, causing execution to continue into subsequent cases. Without break, the program executes all statements from the matched case through the end of the switch or until encountering a break. For example, case 1: case 2: case 3: printf("First quarter"); groups multiple cases together. While this can be useful for combining cases with identical actions, unintentional fall-through is a common source of bugs. Always document intentional fall-through with comments like /* fall through */ to distinguish it from mistakes and maintain code clarity for future developers.

#include 

int main() {
    int month = 2;
    int days;
    
    printf("Month %d has ", month);
    
    switch (month) {
        case 1:  // January
        case 3:  // March
        case 5:  // May
        case 7:  // July
        case 8:  // August
        case 10: // October
        case 12: // December
            days = 31;
            break;
        case 4:  // April
        case 6:  // June
        case 9:  // September
        case 11: // November
            days = 30;
            break;
        case 2:  // February
            days = 28;  // Not considering leap year
            break;
        default:
            printf("Invalid month!\n");
            return 1;
    }
    
    printf("%d days\n", days);
    
    // Example of intentional fall-through
    int number = 2;
    printf("Number %d is: ", number);
    
    switch (number) {
        case 1:
            printf("One ");
            // Fall through intentionally
        case 2:
            printf("Two ");
            // Fall through intentionally
        case 3:
            printf("Three or less\n");
            break;
        default:
            printf("Greater than three\n");
    }
    
    return 0;
}

Output:

Month 2 has 28 days
Number 2 is: Two Three or less

🔹 Calculator Using Switch

Building a calculator with switch statements demonstrates practical application of character-based case selection and arithmetic operations. The program prompts for two numbers and an operator, then uses switch (operator) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: printf("Invalid operator"); } to perform calculations. This structure makes the code highly readable and maintainable. Adding error handling for division by zero and invalid operators creates a robust calculator, illustrating how switch statements excel in scenarios with discrete, predictable input values.

#include 

int main() {
    double num1 = 10.5, num2 = 3.2;
    char operator = '*';
    double result;
    
    printf("Calculator: %.1f %c %.1f = ", num1, operator, num2);
    
    switch (operator) {
        case '+':
            result = num1 + num2;
            printf("%.2f\n", result);
            break;
        case '-':
            result = num1 - num2;
            printf("%.2f\n", result);
            break;
        case '*':
            result = num1 * num2;
            printf("%.2f\n", result);
            break;
        case '/':
            if (num2 != 0) {
                result = num1 / num2;
                printf("%.2f\n", result);
            } else {
                printf("Error: Division by zero!\n");
            }
            break;
        case '%':
            printf("Error: Modulus not supported for floating point!\n");
            break;
        default:
            printf("Error: Invalid operator!\n");
            break;
    }
    
    // Integer modulus example
    int a = 17, b = 5;
    char op = '%';
    
    printf("Integer operation: %d %c %d = ", a, op, b);
    switch (op) {
        case '%':
            if (b != 0) {
                printf("%d\n", a % b);
            } else {
                printf("Error: Division by zero!\n");
            }
            break;
    }
    
    return 0;
}

Output:

Calculator: 10.5 * 3.2 = 33.60
Integer operation: 17 % 5 = 2

🔹 Switch vs If-Else Comparison

Choosing between switch statements and if-else chains depends on the nature of conditions you're evaluating in your program. Switch statements work best with discrete, constant values like integers, characters, or enums, offering cleaner syntax and potentially better performance through jump tables. However, if-else statements are more flexible, supporting ranges (if (age >= 18 && age < 65)), complex boolean expressions, and non-constant conditions. Use switch when checking a single variable against multiple specific values; use if-else for range checking, multiple variable comparisons, or when conditions involve calculations. Both structures achieve the same logical outcomes, but proper selection improves code readability and maintainability significantly.

✅ Use Switch When:

  • Multiple exact values: Comparing a variable against many specific values
  • Integer/character values: Working with int, char, or enum types
  • Cleaner code: Many conditions make if-else messy
  • Performance: Compiler can optimize switch better

✅ Use If-Else When:

  • Range conditions: Checking if value is within a range
  • Complex conditions: Using logical operators (&&, ||)
  • Different data types: Comparing strings, floats, etc.
  • Boolean logic: True/false conditions
// Good for switch
switch (day_of_week) {
    case 1: printf("Monday"); break;
    case 2: printf("Tuesday"); break;
    // ... more cases
}

// Better with if-else
if (age >= 18 && age <= 65) {
    printf("Working age");
} else if (temperature > 100.5) {
    printf("Fever");
}

🧠 Test Your Knowledge

What happens if you forget to put 'break' in a switch case?