Cprogramming 简明教程

C - Nested Switch Statements

在外部 switch 的语句序列一部分中具有 switch 是可能的。即使内部和外部 switch 的大小写常数包含通用值,也不会出现冲突。

It is possible to have a switch as a part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.

Syntax

nested switch 语句的语法如下 −

The syntax for a nested switch statement is as follows −

switch(ch1){
   case 'A':
   printf("This A is part of outer switch" );
   switch(ch2) {
      case 'A':
         printf("This A is part of inner switch" );
         break;
      case 'B':  /* case code */
   }
   break;
   case 'B':  /* case code */
}

Example

请看以下示例:

Take a look at the following example −

#include <stdio.h>
int main (){

   /* local variable definition */
   int a = 100;
   int b = 200;

   switch(a){
      case 100:
      printf("This is part of outer switch\n", a);

      switch(b){
         case 200:
         printf("This is part of inner switch\n", a);
      }
   }
   printf("Exact value of a is: %d\n", a);
   printf("Exact value of b is: %d\n", b);
   return 0;
}

Output

编译并执行上述代码会产生以下输出:

When the above code is compiled and executed, it produces the following output −

This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

Nested Switch-Case Statements in C

就像 nested if–else ,您也可以嵌套 switch-case 结构。您可以在外部 switch 范围的一个或多个 case 标签的代码块内分别包含一个不同的 switch-case 结构。

Just like nested if–else, you can have nested switch-case constructs. You may have a different switch-case construct each inside the code block of one or more case labels of the outer switch scope.

可以按照下列方法嵌套 switch-case −

The nesting of switch-case can be done as follows −

switch (exp1){
   case val1:
   switch (exp2){
      case val_a:
         stmts;
         break;
      case val_b:
         stmts;
         break;
   }
   case val2:
   switch (expr2){
      case val_c:
         stmts;
         break;
      case val_d:
         stmts;
         break;
   }
}

Example

下面是一个演示 C 中嵌套 Switch 语句语法的简单程序 −

Here is a simple program to demonstrate the syntax of Nested Switch Statements in C −

#include <stdio.h>
int main(){
   int x = 1, y = 'b', z='X';

   // Outer Switch
   switch (x){
      case 1:
      printf("Case 1 \n");

      switch (y){
         case 'a':
            printf("Case a \n");
            break;
         case 'b':
            printf("Case b \n");
            break;
      }
      break;

      case 2:
      printf("Case 2 \n");
      switch (z){
         case 'X':
            printf("Case X \n");
            break;
         case 'Y':
            printf("Case Y \n");
            break;
      }
   }
   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

Case 1
Case b

更改变量的值 ( xyz ),并再次检查输出。输出取决于这三个变量的值。

Change the values of the variables (x, y, and z) and check the output again. The output depends on the values of these three variables.