Switch case labels in random order



In this example we are checking the results when switch case labels in random order is written inside c program

Switch case labels in random order

void main() {
   int choice = 7;

   switch (choice)
   {
   default:
      printf("I am in Default");

   case 1:
      printf("I am in case 1");
      break;

   case 2:
      printf("I am in case 2");
      break;

   case 3:
      printf("I am in case 3");
      break;
   }
}

Options : Guess the Output

  1. I am in Default I am in Case 1
  2. I am in Case 1
  3. I am in Default
  4. None of these

Explanation :

Firstly let me print output of the above program –

I am in Default 
I am in Case 1

Now if you see the above program then you can notice one thing we have choice = 7 means default case would be executed.

Compiler predicts which case we need to execute before going inside switch case, but while execution it checks each case label from top to bottom. In this situation default is written at first position so compiler goes inside the default case.

Also read Switch Case rules

Inside the default it will print following statement –

printf("I am in Default");

Once condition is checked and case statement is executed then switch case wont check the condition again, it starts executing all the remaining cases written below current case.

default:
   printf("I am in Default");
case 1:
   printf("I am in case 1");
   break;

We have written case 1 exactly after the default case so case 1 will be executed. As we have written break statement inside the case 1, it terminates the switch

If we write the above program like this by including break statement inside default case –

default:
   printf("I am in Default");
   break;
case 1:
   printf("I am in case 1");
   break;

then only statements inside default would be printed on the screen

Here is nice discussion about the effects caused over efficiency when we place switch case labels in random order