C switch statement

In C, a switch statement is a control flow statement that allows a variable or expression to be tested against a series of values (called cases). It helps simplify multiple if-else conditions when checking for multiple possible values of a single variable.

Syntax:


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

Key Points:

  1. switch checks the value of the expression.
  2. Each case corresponds to a possible value of the expression.
  3. The break statement ends the switch block after a matching case is found.
  4. The default case runs if none of the cases match the expression.

Example 1:


#include <stdio.h>

int main() {
     int day = 2;

        switch (day)
        {
            case 1:
                printf("Monday");
                break;
            case 2:
                printf("Tuesday");
                break;
            case 3:
                printf("Wednesday");
                break;
          
            default:
                printf("Invalid day");
                break;
        }
    return 0;
}

Output:

Tuesday

Example 2:


#include <stdio.h>

int main() {
    enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
    
    // Initialize today as Friday
    enum Day today = Friday;

    switch (today) {
        case Monday:
            printf("Start of the work week!");
            break;
        case Friday:
            printf("End of the work week!");
            break;
        default:
            printf("It's a regular day.");
            break;
    }

    return 0;
}

Output:

End of the work week!