C Switch Statement

C Switch Statement


nsider the example: Print English words, given a digit between 0-9. Below is how the implementation in Switch looks


 
int a = 9;
switch(a)
{
 case 1: printf("I am One\n");
         break;
 case 2: printf("I am Two\n");
         break;
 case 3: printf("I an Three\n");
         break;
 case 4: printf("I am Four\n");
         break;
 case 5: printf("I am Five\n");
         break;
 case 6: printf("I am Six\n");
         break;
 case 7: printf("I am Seven\n");
         break;
 case 8: printf("I am Eight\n");
 case 9: printf("I am Nine\n");
 case 0: printf("I am Zero\n");
 default: printf("I am default\n");
}

The output of this switch is :\nI am Nine\nI am Zero\nI am default

Explanation: The ‘a’ variable value is 9, this is compared against the case values and a match is found. All the statements following case 9 are executed until a break statement or end of switch are encountered. Since there are no break statements(break is optional), all the statements following case 9 are executed. (Which is a weird output, if we gave 9 as input, we only want to print I am Nine as output, so we have to write break immediately after printf(“I am Nine”) to stop the flow)

For instance, If the ‘a’ value is 5 instead of 9 in the above switch block. The output of the switch would be: I am Five. That’s it. This is because there is a break statement following case 5. Which interrupted the flow and control came out of the switch block.

So, as seen in the above example the flow of control in a switch is determined by the presence of break inside the case,

  • If break is present, after the matching case statements are executed control will come out of the switch
  • If break is not present after the matching case statements are executed it will continue to execute all the statements in the below cases including default, till the end of switch statement.
  1. If no match is found between in switch and s in case, then
  • control goes to default block if it exists( default is optional ),
  • If default block is not written in the switch then, control comes