C Nested Switch Statements: Mastering Complex Decision-Making

Learn how to use nested switch statements in C to handle complex decision-making scenarios. Explore how switch cases can be nested within each other without conflict, even when using identical case values in both switches.



C - Nested Switch Statements

You can nest switch statements within each other. This allows for more complex decision-making without conflicts, even if the case values are the same in both switches.

Syntax

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;
}
break;
case 'B':
// case code
break;
}
    
Output

This A is part of outer switch
This A is part of inner switch
    

Example

Example Code

#include <stdio.h>
int main() {
int a = 100;
int b = 200;

switch(a) {
case 100:
    printf("This is part of outer switch\\n");

    switch(b) {
        case 200:
            printf("This is part of inner switch\\n");
            break;
    }
    break;
}

printf("Exact value of a is: %d\\n", a);
printf("Exact value of b is: %d\\n", b);
return 0;
}
    
Output

This is part of outer switch
This is part of inner switch
Exact value of a is: 100
Exact value of b is: 200
    

Nested Switch-Case Statements in C

Nested switch-case constructs allow you to place one switch-case construct inside another. This can help manage complex decision trees more efficiently.

Syntax

switch (exp1) {
case val1:
switch (exp2) {
    case val_a:
        // statements
        break;
    case val_b:
        // statements
        break;
}
break;
case val2:
switch (expr2) {
    case val_c:
        // statements
        break;
    case val_d:
        // statements
        break;
}
break;
}
    
Example Code

#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;
    }
    break;
}
return 0;
}
    
Output

Case 1
Case b