How to use the switch statement in the C language?

In C language, the switch statement is used to execute different operations based on the different values of a variable. Its basic syntax is as follows:

switch (expression) {
    case constant1:
        // code block;
        break;
    case constant2:
        // code block;
        break;
    ...
    default:
        // code block;
}
  1. The expression is an expression whose value will be compared with the constant value of each case.
  2. Case is a keyword followed by a constant, indicating the block of code that should be executed for that branch.
  3. The keyword “break” is crucial in a switch statement to exit and prevent the execution of subsequent case branches. If a break is not included, it will continue to execute the next case branch until a break is encountered or the switch statement ends.
  4. The default branch is optional and is used to handle cases where none of the case branches are matched.

The following is a simple example demonstrating the usage of a switch statement.

#include <stdio.h>

int main() {
    int choice;

    printf("请选择一个数字(1-3):");
    scanf("%d", &choice);

    switch (choice) {
        case 1:
            printf("你选择了数字1\n");
            break;
        case 2:
            printf("你选择了数字2\n");
            break;
        case 3:
            printf("你选择了数字3\n");
            break;
        default:
            printf("无效的选择\n");
    }
    
    return 0;
}

In this example, based on the number input by the user, the switch statement will execute the corresponding code block and output the corresponding result. If the user inputs a number that is not 1, 2, or 3, the default branch will execute and output “Invalid selection”.

bannerAds