Detailed explanation of the usage of switch-case

General form:

switch (expression){

    case const-expression 1: statement 1;
     case const-expression 2: statement 2;
    case constant expression n: statement n;
     default : statement n+1 ;
}

meaning is:

Calculate the value of the expression first, and then compare it with the constant expression after the case one by one;

If it is not equal, continue to compare, if it is not equal, execute the statement after default;

If it is equal to a constant expression, the execution starts from the statement after the expression, and executes all the statements after the case.

Different from the if statement: if the judgment is true in the if statement, only the statement after the judgment will be executed, and the if statement will jump out after the execution, and no other if statements will be executed;

The switch statement does not break out of the loop after executing the statement that is judged to be true, but continues to execute all subsequent case statements.

Add a break statement after each case statement, so that the switch statement can be jumped out after each execution, so as to avoid outputting unexpected results.

 

Notice:

         1. The constant expressions after the case cannot be the same;

         2. There can be multiple statements after the case and are not enclosed in curly braces;

          3. The order of case and default clauses can be changed successively, and the default clause can be omitted;     

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325263723&siteId=291194637