switch in c

In c, switch is also a decision making statement. It checks the expression against available cases inside switch, if any case is matched with expression value, then it executes related case statements, If not matched, then default block statements executes.

Syntax

switch(expression)
{
  case:
  // set of statements
  break;
 case:
  // set of statements
  break;
 case:
  // set of statements
  break;
 default:
  // set of statements
}

In switch, there can be any number of cases.

Break Keyword in switch

  1. In switch, every case ends with break keyword.
  2. Break is a jump statement, which when encountered, takes the control out of switch statement. Hence, it allows to skip checking of all available cases of switch in c.

default keyword in switch

  1. It must be written always at the end of switch.
  2. default has no break keyword, because after it, there are no cases.

Example

#include<stdio.h>

void main()
{
    int month = 1;
    switch(month){
      case 1:
       printf("January");
      break;
      case 2:
       printf("February");
      break;
      case 3:
       printf("March");
      break;
      default:
       printf("Hello, How are you");
    }
}

Explanation

  1. Above example, variable month is declared and initialized with value 1.
  2. In switch(month), the value of month is matched against available cases.
  3. If matched then, switch executes the related set of statements.
  4. If not matched, then executes, default statements.

Multiple cases in switch

In c, switch allows to use multiple cases for same set of statements.

#include<stdio.h>

void main()
{
    int month = 5;
    switch(month){
      case 1:
      case 2:
      case 3:
       printf("Winter Season");
      break;
      case 4:
      case 5:
      case 6:
       printf("Summer Season");
      break;
      default:
       printf("Rainy Season");
    }
}
Output:
Summer Season