Cprogramming 简明教程

Switch Statement in C

一个 switch statement 允许变量根据一个值列表进行相等性测试。每个值称为一个 case ,而正在进行 switch 的变量会针对每个 switch case 进行检查。

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

C switch-case Statement

switch-case 语句是 C 中的 decision-making statementif-else 语句提供两个要执行的备用动作,而 switch-case 构造是一个多路分支语句。C 中的 switch 语句通过针对多个值评估单个变量并根据匹配执行特定代码,来简化多路选择。它允许对一个 variable 进行相等性测试,以针对一个值列表进行相等性测试。

The switch-case statement is a decision-making statement in C. The if-else statement provides two alternative actions to be performed, whereas the switch-case construct is a multi-way branching statement. A switch statement in C simplifies multi-way choices by evaluating a single variable against multiple values, executing specific code based on the match. It allows a variable to be tested for equality against a list of values.

Syntax of switch-case Statement

程序的流程可以将行执行转换为满足给定 case 的分支。switch-case 构造的示意图表示如下 −

The flow of the program can switch the line execution to a branch that satisfies a given case. The schematic representation of the usage of switch-case construct is as follows −

switch (Expression){

   // if expr equals Value1
   case Value1:
      Statement1;
      Statement2;
      break;

   // if expr equals Value2
   case Value2:
      Statement1;
      Statement2;
      break;
      .
      .
   // if expr is other than the specific values above
   default:
      Statement1;
      Statement2;
}

How switch-case Statement Work?

switch 关键字前面的括号包含一个表达式。该表达式应计算为一个整数或一个字符。在括号后的花括号中,表达式的不同可能值会形成 case 标签。

The parenthesis in front of the switch keyword holds an expression. The expression should evaluate to an integer or a character. Inside the curly brackets after the parenthesis, different possible values of the expression form the case labels.

在 case 标签前面的冒号 (:) 后的一个或多个语句形成一个块,当表达式等于标签值时将执行该块。

One or more statements after a colon(:) in front of the case label forms a block to be executed when the expression equals the value of the label.

你可以将 switch-case 从字面上翻译为“如果表达式等于 value1,则执行 block1”,等等。

You can literally translate a switch-case as "in case the expression equals value1, execute the block1", and so on.

C 会使用每个标签值检查表达式,并执行第一个匹配前面的块。每个 case 块都有一个 break 作为最后一个语句。 break statement 会将控制权带出 switch 构造的范围。

C checks the expression with each label value, and executes the block in front of the first match. Each case block has a break as the last statement. The break statement takes the control out of the scope of the switch construct.

你还可以将 default case 定义为 switch 构造中的最后一个选项。当表达式与任何较早的 case 值都不匹配时,将执行 default case 块。

You can also define a default case as the last option in the switch construct. The default case block is executed when the expression doesn’t match with any of the earlier case values.

Flowchart of switch-case Statement

表示 C 中的 switch-case 构造的流程图如下 −

The flowchart that represents the switch-case construct in C is as follows −

switch statement

Rules for Using the switch-case Statement

以下规则适用于 switch 语句 −

The following rules apply to a switch statement −

  1. The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.

  2. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

  3. The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.

  4. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

  5. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

  6. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

  7. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

switch-case statement 充当 if-else 语句级联的简洁替代方案,尤其是在“if”中的布尔表达式基于“=”运算符时。

The switch-case statement acts as a compact alternative to cascade of if-else statements, particularly when the Boolean expression in "if" is based on the "=" operator.

如果 if (或 else )块中有多个语句,则你必须将它们放在花括号内。因此,如果你的代码有很多 ifelse 语句,则具有那么多开闭花括号的代码看起来很笨拙。switch-case 替代方案是一个简洁且无杂乱的解决方案。

If there are more than one statements in an if (or else) block, you must put them inside curly brackets. Hence, if your code has many if and else statements, the code with that many opening and closing curly brackets appears clumsy. The switch-case alternative is a compact and clutter-free solution.

C switch-case Statement Examples

练习以下示例以了解 C 编程语言中的 switch case 语句 −

Practice the following examples to learn the switch case statements in C programming language −

Example 1

在下面的代码中,一系列 if-else statements 根据“ch”变量的值(“m”、“a”或“e”,分别代表早上、下午或晚上)打印三个不同的问候消息。

In the following code, a series of if-else statements print three different greeting messages based on the value of a "ch" variable ("m", "a" or "e" for morning, afternoon or evening).

#include <stdio.h>

int main(){

   /* local variable definition */
   char ch = 'e';
   printf("Time code: %c\n\n", ch);

   if (ch == 'm')
      printf("Good Morning");

   else if (ch == 'a')
      printf("Good Afternoon");
   else
      printf("Good Evening");

   return 0;
}

上面代码中的 if-else 逻辑被下面代码中的 switch-case 结构所取代 −

The if-else logic in the above code is replaced by the switch-case construct in the code below −

#include <stdio.h>

int main (){

   // local variable definition
   char ch = 'm';
   printf("Time code: %c\n\n", ch);

   switch (ch){

      case 'a':
         printf("Good Afternoon\n");
         break;

      case 'e':
         printf("Good Evening\n");
         break;

      case 'm':
         printf("Good Morning\n");
   }
   return 0;
}

更改“ch”变量的值并检查输出。对于 ch = 'm',我们得到以下输出 −

Change the value of "ch" variable and check the output. For ch = 'm', we get the following output −

Time code: m

Good Morning

这里使用 break 非常重要。每个情况对应的语句块以 break 语句结束。如果 break 语句没有使用,会怎样?

The use of break is very important here. The block of statements corresponding to each case ends with a break statement. What if the break statement is not used?

switch-case 的工作原理如下:当程序进入 switch 结构时,它开始将转换表达式的值与情况进行比较,并执行其第一个匹配的块。 break 导致控制脱离 switch 范围。如果未找到 break ,后续块也将被执行,从而导致结果不正确。

The switch-case works like this: As the program enters the switch construct, it starts comparing the value of switching expression with the cases, and executes the block of its first match. The break causes the control to go out of the switch scope. If break is not found, the subsequent block also gets executed, leading to incorrect result.

Example 2: Switch Statement without using Break

让我们注释掉上面代码中的所有 break 语句。

Let us comment out all the break statements in the above code.

#include <stdio.h>

int main (){

   /* local variable definition */
   char ch = 'a';
   printf("Time code: %c\n\n", ch);

   switch (ch){
      case 'a':
         printf("Good Afternoon\n");
         // break;

      case 'e':
         printf("Good Evening\n");
         // break;

      case 'm':
         printf("Good Morning\n");
   }
   return 0;
}

你希望打印“早上好”的消息,但是你发现所有三条消息都打印出来了!

You expect the "Good Morning" message to be printed, but you find all the three messages printed!

Time code: a

Good Afternoon
Good Evening
Good Morning

这是因为 C 在块的结尾没有 break 语句时,会贯穿后续的情况块。

This is because C falls through the subsequent case blocks in the absence of break statements at the end of the blocks.

Example 3: Grade Checker Program using Switch Statement

在下面的程序中,“grade”是转换变量。对于不同等级的情况,将打印相应的成绩消息。

In the following program, "grade" is the switching variable. For different cases of grades, the corresponding result messages will be printed.

#include <stdio.h>

int main(){

   /* local variable definition */
   char grade = 'B';

   switch(grade){
      case 'A' :
         printf("Outstanding!\n" );
         break;
      case 'B':
        printf("Excellent!\n");
        break;
      case 'C':
         printf("Well Done\n" );
         break;
      case 'D':
         printf("You passed\n" );
         break;
      case 'F':
         printf("Better try again\n" );
         break;
      default :
         printf("Invalid grade\n" );
   }
   printf("Your grade is  %c\n", grade);

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

Excellent!
Your grade is  B

现在更改“grade”的值(它是“char”变量)并检查输出。

Now change the value of "grade" (it is a "char" variable) and check the outputs.

Example 4: Menu-based Calculator for Arithmetic Operations using Switch

以下示例显示了一个用于算术运算的菜单。根据运算符代码的值(1、2、3 或 4),对两个值进行加法、减法、乘法或除法。如果运算符代码是其他内容,则执行默认情况。

The following example displays a menu for arithmetic operations. Based on the value of the operator code (1, 2, 3, or 4), addition, subtraction, multiplication or division of two values is done. If the operation code is something else, the default case is executed.

#include <stdio.h>

int main (){

   // local variable definition
   int a = 10, b = 5;

   // Run the program with other values 2, 3, 4, 5
   int op = 1;
   float result;

   printf("1: addition\n");
   printf("2: subtraction\n");
   printf("3: multiplication\n");
   printf("4: division\n");

   printf("\na: %d b: %d : op: %d\n", a, b, op);
   switch (op){
      case 1:
         result = a + b;
         break;
      case 2:
         result = a - b;
         break;
      case 3:
         result = a * b;
         break;
      case 4:
         result = a / b;
         break;
      default:
         printf("Invalid operation\n");
   }
   if (op >= 1 && op <= 4)
      printf("Result: %6.2f", result);

   return 0;
}
1: addition
2: subtraction
3: multiplication
4: division

a: 10 b: 5 : op: 1
Result:  15.00

对于“op”的其他值(2、3 和 4),您将获得以下输出 −

For other values of "op" (2, 3, and 4), you will get the following outputs −

a: 10 b: 5 : op: 2
Result:   5.00

a: 10 b: 5 : op: 3
Result:  50.00

a: 10 b: 5 : op: 4
Result:   2.00

a: 10 b: 5 : op: 5
Invalid operation

Switch Statement by Combining Multiple Cases

可以将多个情况一起编写以执行一个代码块。当其中任何一个值匹配时,这些组合情况的主体将执行。如果您遇到这种情况,其中同一代码块要针对表达式的多个情况标签执行,您可以通过将两个情况一个放在另一个的下方来合并它们,如下所示 −

Multiple cases can be written together to execute one block of code. When any of them case value matches, the body of these combined cases executes. If you have a situation where the same code block is to be executed for more than one case labels of an expression, you can combine them by putting the two cases one below the other, as shown below −

Syntax

switch (exp) {
   case 1:
   case 2:
      statements;
      break;
   case 3:
      statements;
      break;
   default:
      printf("%c is a non-alphanumeric character\n", ch);
}

您还可以使用省略号 (…​) 来合并表达式的一系列值。例如,若要将转换变量的值与 1 到 10 之间的任何数字匹配,可以使用“case 1 … 10”

You can also use the ellipsis (…) to combine a range of values for an expression. For example, to match the value of switching variable with any number between 1 to 10, you can use "case 1 … 10"

Example 1

#include <stdio.h>

int main (){

   // local variable definition
   int number = 5;

   switch (number){

      case 1 ... 10:
         printf("The number is between 1 and 10\n");
         break;

      default:
         printf("The number is not between 1 and 10\n");
   }
   return 0;
}

运行代码并检查其输出。对于“number = 5”,我们得到以下输出 −

Run the code and check its output. For "number = 5", we get the following output −

The number is between 1 and 10

Example 2

下面的程序检查给定的字符变量的值是否存储了小写字母、大写字母、数字或任何其他键。

The following program checks whether the value of the given char variable stores a lowercase alphabet, an uppercase alphabet, a digit, or any other key.

#include <stdio.h>

int main (){

   char ch = 'g';

   switch (ch){
      case 'a' ... 'z':
         printf("%c is a lowercase alphabet\n", ch);
         break;

      case 'A' ... 'Z':
         printf("%c is an uppercase alphabet\n", ch);
         break;

      case 48 ... 57:
         printf("%c is a digit\n", ch);
         break;

      default:
         printf("%c is a non-alphanumeric character\n", ch);
   }
   return 0;
}

对于 ch = 'g' ,我们得到以下输出 −

For ch = 'g', we get the following output −

g is a lowercase alphabet

使用不同的“ch”值测试代码输出。

Test the code output with different values of "ch".