Latest web development tutorials

C nested switch statements

Analyzing C Analyzing C

You can put aswitch as part of a sequence of statements of the external switch,that can be used in anotherswitchstatement within aswitchstatement. Even in case of internal and external switch constant contains common values, there is no contradiction.

grammar

C language syntax fornested switch statement:

switch(ch1) {
   case 'A': 
      printf("这个 A 是外部 switch 的一部分" );
      switch(ch2) {
         case 'A':
            printf("这个 A 是内部 switch 的一部分" );
            break;
         case 'B': /* 内部 B case 代码 */
      }
      break;
   case 'B': /* 外部 B case 代码 */
}

Examples

#include <stdio.h>
 
int main ()
{
   /* 局部变量定义 */
   int a = 100;
   int b = 200;
 
   switch(a) {
      case 100: 
         printf("这是外部 switch 的一部分\n");
         switch(b) {
            case 200:
               printf("这是内部 switch 的一部分\n");
         }
   }
   printf("a 的准确值是 %d\n", a );
   printf("b 的准确值是 %d\n", b );
 
   return 0;
}

When the above code is compiled and executed, it produces the following results:

这是外部 switch 的一部分
这是内部 switch 的一部分
a 的准确值是 100
b 的准确值是 200

Analyzing C Analyzing C