C++ Nested Switch Statement
You can have a switch as part of the statement sequence of an outer switch. This is called nested switch statements. Even if the case constants of the inner and outer switch contain common values, there is no conflict.
The switch statement in C++ allows for at least 256 levels of nesting.
Syntax
The syntax for a nested switch statement in C++:
switch(ch1) {
case 'A':
cout << "This A is part of the outer switch";
switch(ch2) {
case 'A':
cout << "This A is part of the inner switch";
break;
case 'B': // Inner B case code
}
break;
case 'B': // Outer B case code
}
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 << "Exact value of a is " << a << endl;
cout << "Exact value of b is " << b << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
This is part of the outer switch
This is part of the inner switch
Exact value of a is 100
Exact value of b is 200