Switch Statements

Lesson 20
Author : Afrixi
Last Updated : January, 2023
C - Programming Language
This course covers the basics of programming in C.

Switch statements are a type of conditional statement in the C programming language. They allow you to execute different code blocks based on the value of a variable or expression.

The syntax for a switch statement in C is as follows:

switch(expression) {
   case constant1:
      // code to execute if expression is equal to constant1
      break;
   case constant2:
      // code to execute if expression is equal to constant2
      break;
   ...
   default:
      // code to execute if expression does not match any constant
}

Here, the expression is the variable or expression whose value we are checking. The constants are the possible values of the expression that we are checking for. The code block corresponding to the first constant that matches the value of the expression is executed. If none of the constants match the expression, the code block under the default label is executed.

Let’s look at an example:

#include <stdio.h>

int main() {
   int dayOfWeek = 2;
   
   switch(dayOfWeek) {
      case 1:
         printf("Monday");
         break;
      case 2:
         printf("Tuesday");
         break;
      case 3:
         printf("Wednesday");
         break;
      case 4:
         printf("Thursday");
         break;
      case 5:
         printf("Friday");
         break;
      default:
         printf("Weekend");
         break;
   }
   
   return 0;
}

In this example, we have a variable dayOfWeek with a value of 2. The switch statement checks the value of dayOfWeek, and since it matches the case 2, the code block under that label is executed, which prints “Tuesday” to the console.

If we were to change the value of dayOfWeek to 6, the default case would be executed, which would print “Weekend” to the console.

Switch statements can be a more concise way to handle multiple conditional statements in cases where the conditions are based on a single variable or expression.