C Switch

In C programming, the switch statement is a control structure used for making decisions based on the value of an expression. It allows you to execute different code blocks depending on the value of an expression. switch is often used when you have a single expression with multiple possible values, and you want to execute different code for each value.

Basic Syntax of the switch Statement:

        
switch (expression) {
    case value1:
        // Code to be executed if expression is equal to value1
        break; // Optional, to exit the switch block
    case value2:
        // Code to be executed if expression is equal to value2
        break;
    // ...
    default:
        // Code to be executed if none of the cases match
}
        
    

Here's an explanation of the components:

  • switch: This is the keyword that starts the switch statement.
  • expression: This is the expression whose value is tested against each case. The expression should result in an integral value, like an integer or a character.
  • case value1: This is a label specifying a value that the expression can have. If the expression equals value1, the code block associated with this case will be executed. You can have multiple case labels.
  • break: The break statement is optional but commonly used. It is used to exit the switch block after the associated code block has been executed. If you omit break, execution will continue to the next case, which can lead to unexpected behavior.
  • default: This is also optional. If none of the case values match the expression, the code block associated with default will be executed. It serves as a fallback option.

Here's an example of a switch statement in C:

        
#include <stdio.h>

int main() {
    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("Weekend\n");
    }

    return 0;
}
        
    

In this example, the switch statement checks the value of the variable day. Depending on the value of day, it will print the corresponding day of the week. Since day is 3 in this example, it will print "Wednesday."

The switch statement provides a convenient way to handle multiple cases with different code blocks, making the code more organized and readable when compared to using a series of if-else if statements.