C - Switch Case

The switch statement provides a convenient way to select one of several code blocks to execute based on the value of a given expression. It allows you to streamline and simplify code that involves multiple conditional statements.

switch (expression)
{
    case constant1:
        // Code to be executed if expression matches constant1
        break;
    case constant2:
        // Code to be executed if expression matches constant2
        break;
    // Add more cases as needed
    default:
        // Code to be executed if expression doesn't match any constants
}

The expression is evaluated, and its value is compared against the constants in each case.

If a match is found, the corresponding code block is executed until a break statement is encountered or the end of the switch statement is reached.

If no match is found, the code block under the default label is executed (optional).

The break statement is used to exit the switch statement after a case is executed. Without a break statement, the control will fall through to the next case, and subsequent code blocks will be executed until a break statement is encountered or the end of the switch statement is reached.

int day = 3;
switch (day)
{
    case 1:
        printf("Monday\n");
        break;
    case 2:
        printf("Tuesday\n");
        break;
    case 3:
        printf("Wednesday\n");
        break;
    case 4:
        printf("Thursday\n");
        break;
    case 5:
        printf("Friday\n");
        break;
    default:
        printf("Invalid day\n");
}

In this example, the value of the day variable is compared against each case. Since day is 3, the code block under case 3 is executed, printing "Wednesday".

The switch statement is useful when you have a limited number of possibilities to consider and want to avoid multiple if-else statements. It can make your code more concise and readable in such cases.