Easy Tutorial
❮ C Function Qsort C Examples String Copy ❯

Nested Switch Statements

C Decision

You can place a switch as part of the statement sequence of an outer switch. This means you can use one switch statement inside another switch statement. There is no conflict even if the case constants of the inner and outer switches contain common values.

Syntax

The syntax for a nested switch statement in C:

switch(ch1) {
   case 'A': 
      printf("This A is part of the outer switch");
      switch(ch2) {
         case 'A':
            printf("This A is part of the inner switch");
            break;
         case 'B': /* Inner B case code */
      }
      break;
   case 'B': /* Outer B case code */
}

Example

#include <stdio.h>

int main ()
{
   /* Local variable definition */
   int a = 100;
   int b = 200;

   switch(a) {
      case 100: 
         printf("This is part of the outer switch\n");
         switch(b) {
            case 200:
               printf("This is part of the inner switch\n");
         }
   }
   printf("The exact value of a is %d\n", a );
   printf("The exact value of b is %d\n", b );

   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
The exact value of a is 100
The exact value of b is 200

C Decision

❮ C Function Qsort C Examples String Copy ❯