C++ Nested switch Statements
You can place aswitchas an externalswitchpart of the statement sequence, i.e., can be in aswitchUse another within a statementswitchstatement. Even if the case constants of the inner and outer switch contain common values, there is no contradiction.
The switch statement in C++ allows at least 256 nesting levels.
Syntax
In C++Nested switchSyntax of the statement:
switch(ch1) {
case 'A':
cout << "这个 A 是外部 switch 的一部分";
switch(ch2) {
case 'A':
cout << "这个 A 是内部 switch 的一部分";
break;
case 'B': // 内部 B case 代码
}
break;
case 'B': // 外部 B case 代码
}
Example
Example
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration
int a = 100;
int b = 200;
switch(a) {
case 100:
cout << "This is part of the outer switch" << endl;
switch(b) {
case 200:
cout << "This is part of the inner switch" << endl;
}
}
cout << "The exact value of a is " << a << endl;
cout << "The exact value of b is " << b << endl;
return 0;
}
using namespace std;
int main ()
{
// Local variable declaration
int a = 100;
int b = 200;
switch(a) {
case 100:
cout << "This is part of the outer switch" << endl;
switch(b) {
case 200:
cout << "This is part of the inner switch" << endl;
}
}
cout << "The exact value of a is " << a << endl;
cout << "The exact value of b is " << b << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
这是外部 switch 的一部分 这是内部 switch 的一部分 a 的准确值是 100 b 的准确值是 200other extensions