C - Statement switch Statement

Introduction

The switch statement chooses action from a set of possible actions, based on the result of an integer expression.

The general way of describing the switch statement is as follows:

switch(integer_expression)
{
  case constant_expression_1:
    statements_1;
    break;
    ....
  case constant_expression_n:
    statements_n;
    break;
  default:
    statements;
    break;
}

Because an enumeration type is an integer type, you can use a variable of an enumeration type to control a switch.

Demo

#include <stdio.h>
int main()/*  ww w. j a  v  a2  s  .c om*/
{
  enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
  enum Weekday today = Wednesday;
  switch (today)
  {
  case Sunday:
    printf("Today is Sunday.");
    break;
  case Monday:
    printf("Today is Monday.");
    break;
  case Tuesday:
    printf("Today is Tuesday.");
    break;
  case Wednesday:
    printf("Today is Wednesday.");
    break;
  case Thursday:
    printf("Today is Thursday.");
    break;
  case Friday:
    printf("Today is Friday.");
    break;
  case Saturday:
    printf("Today is Saturday.");
    break;
  }

  return 0;
}

Result

This switch selects the case that corresponds to the value of the variable today.

There's no default case in the switch, but you could put one in to guard against an invalid value for today.

Related Topics

Quiz

Example

Exercise