Latest web development tutorials

C ++ nested switch statement

C ++ judgment C ++ judgment

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.

C ++ switch statement allows at least 256 levels of nesting.

grammar

C ++nested switch statement syntax:

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

Examples

#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   int a = 100;
   int b = 200;
 
   switch(a) {
      case 100: 
         cout << "这是外部 switch 的一部分" << endl;
         switch(b) {
            case 200:
               cout << "这是内部 switch 的一部分" << endl;
         }
   }
   cout << "a 的准确值是 " << a << endl;
   cout << "b 的准确值是 " << b << endl;
 
   return 0;
}

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

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

C ++ judgment C ++ judgment