a shot of dev knowledge

Related tags

How to use the switch statement in C

A switch statement allows a variable to be tested against several values for equality. Each of these values is called a case. Once a matching case is found, its particular block of code is executed. It is an alternative to the more common if-else statement.

Syntax

switch(expression)
{
   case constant_1 :
      // Code to be executed if expression == constant_1
      break;
	
   case constant_2 :
      // Code to be executed if expression == constant_2;
      break;
  
   default : // the default case is optional
      // Code to be executed if none of the cases match.
}

Rules

There are some rules to keep in mind while writing switch statements:

  • The expression in the switch can be a variable or an expression - but it must be an integer or a character.
  • You can have any number of cases however there should not be any duplicates. Switch statements can also be nested within each other.
  • The optional default case is executed when none of the cases above match.
  • The break statement is used to break the flow of control once a case block is executed. While it is optional, without it, all subsequent cases after the matching case will also get executed. Consider the code below to get a clearer idea:

Flow

The following diagram illustrates the flow of control in a switch:

svg viewer

Examples

Since var = 10, the control jumped to the case 10 block - but without any breaks, the flow is not broken and all subsequent case statements are also printed.

Try uncommenting the break statements and note the output. Feel free to experiment with the value of var as well.

Note: A break is not needed after the default case. This is because control would naturally exit the switch statement anyway.

int main() {
  int var = 10;
  switch (var)
    {
      case 5:
          printf("Case 1 executed.");
          // break;
      case 10:
          printf("Case 2 executed. ");
          // break;
      case 15:
          printf("Case 3 executed. ");
          // break;
      case 20:
          printf("Case 4 executed. ");
          // break;
      default:
          printf("Default case executed. ");
    }
}

You can use char's for the switch expression and cases as well. In the code below, option matches case 'b', hence its case block is executed.

int main() {

  char option = 'b';
  switch (option)
    {
      case 'a':
          printf("Case a hit.");
          break;
      case 'b':
          printf("Case b hit. ");
          break;
      case 'c':
          printf("Case c hit. ");
          break;
      default:
          printf("Default case hit.");
    }
}

Related tags

RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring