Switch Case Statement

The switch statement is a multiway branch statement. It provides the easyest way to dispatch the execution to different parts of the codes based on the value of expression. Switch is a control statement that allows a value to change the control of execution. The switch statement allows us to execute one code block among the all alternative blocks. You can do the same thing with the if...else..if statement but the syntax of the switch case statement is much easier to read and write. See the following diagram.

flowchart example

Keynotes about switch case:

  1. Duplicate case values are not allowed.
  2. The default statement is optional but if the switch case statement do not have a default statement, it would run without any problem.
  3. The break statement is used inside the blocks to terminate a statement sequence. When compiler get break statement the switch terminate , and the compiler jumps to the next line following the switch statement.
  4. Nested of switch statements are allowed which means you can have a switch statements inside a another switch. However nested switch statements should be avoided because it makes program more complex and less readable.
example1:

  #include<stdio.h>
  int main(){
   int x = 2;
   switch (x) { 
    case 1: printf("Choice is 1"); 
     break; 
    case 2: printf("Choice is 2"); 
     break; 
    case 3: printf("Choice is 3"); 
     break; 
    default: printf("Choice other than 1, 2 and 3"); 
    break;   
   } 
  return 0;
  }


Output:

  Choice is 2


example2:

  #include<stdio.h>
  int main(){
   int x=5;
   switch (x) { 
    case 1: printf("Choice is 1"); 
     break; 
    case 2: printf("Choice is 2"); 
     break; 
    case 3: printf("Choice is 3"); 
     break; 
    default: printf("Choice other than 1, 2 and 3"); 
     break;   
   } 
  return 0;
 }


Output:

  Choice other than 1, 2 and 3