1. Switch sentence

1. Switch sentence

C language also provides another switch statement for multi branch selection, which generally takes the form of:

switch (expression) 
{ 
case Constant expression1: sentence1;
case Constant expression2: sentence2; 
… 
case Constant expressionn: sentencen;
default : sentence n+1;
} 

Its semantics are: to calculate the value of an expression. And compare them with the constant expression values one by one. When the value of the expression is equal to the value of a constant expression, the subsequent statements are executed, and then no further judgment is made, continuing to execute all statements after the case. If the value of the expression is different from the constant expression after all cases, execute the statement after default.

When using the switch statement, the following points should also be noted:

  1. The values of the constant expressions after the case cannot be the same, otherwise errors may occur.

  2. After the case, multiple statements are allowed and do not need to be enclosed in {}.

  3. The order of each case and default clause can be changed without affecting the program execution result.

  4. The default clause can be omitted.