C - Nested Switch Statements
C - Nested Switch Statements
Syntax
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 −
Open Compiler
#include <stdio.h>
int main (){
switch(a){
case 100:
printf("This is part of outer switch\n", a);
https://www.tutorialspoint.com/cprogramming/nested_switch_statements_in_c.htm 1/4
10/23/24, 11:06 AM C - Nested Switch Statements
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 −
Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
switch (exp1){
case val1:
switch (exp2){
case val_a:
stmts;
break;
case val_b:
stmts;
break;
}
case val2:
switch (expr2){
case val_c:
https://www.tutorialspoint.com/cprogramming/nested_switch_statements_in_c.htm 2/4
10/23/24, 11:06 AM C - Nested Switch Statements
stmts;
break;
case val_d:
stmts;
break;
}
}
Example
Here is a simple program to demonstrate the syntax of Nested Switch Statements in C −
Open Compiler
#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;
https://www.tutorialspoint.com/cprogramming/nested_switch_statements_in_c.htm 3/4
10/23/24, 11:06 AM C - Nested Switch Statements
}
}
return 0;
}
Output
When you run this code, it will produce the following output −
Case 1
Case b
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.
https://www.tutorialspoint.com/cprogramming/nested_switch_statements_in_c.htm 4/4