c
  1. c-switch-statement

C switch Statement

The switch statement is a control flow statement in C that allows a program to evaluate an expression and then execute code based on the value of the expression. It provides an alternative to the if-else-if ladder for making decisions based on multiple conditions.

Syntax

The syntax for the switch statement is as follows:

switch(expression) {
   case constant-expression:
      statement(s);
      break;
   case constant-expression:
      statement(s);
      break;
   /* optional */
   default:
      statement(s);
}
  • expression - An expression that is evaluated once.
  • constant-expression - A unique case value that corresponds to the expression.
  • statement(s) - One or more statements that are executed when a case is selected.
  • break - A keyword that terminates a case and exits the switch statement.

Example

#include <stdio.h>
int main() {
   int num = 2;
   
   switch(num) {
      case 1 :
         printf("Case 1: num = %d\n", num);
         break;
      case 2 :
         printf("Case 2: num = %d\n", num);
         break;
      case 3 :
         printf("Case 3: num = %d\n", num);
         break;
      default :
         printf("Default case\n");
   }
   return 0;
}

Output

The above code will produce the following output:

Case 2: num = 2

Explanation

In the above example, the switch statement evaluates the variable num. If num is equal to 1, the first set of print statements is executed. If num is equal to 2, the second set of print statements is executed. If num is equal to 3, the third set of print statements is executed. If num does not match any of the case values, then the default set of print statements is executed.

Use

The switch statement is commonly used in C programming to execute code based on multiple conditions. It can be a more efficient and straightforward alternative to the if-else-if ladder.

Important Points

  • The switch statement evaluates the expression once and then executes the code for one of the matching cases.
  • The cases must be unique and cannot have the same constant expression value.
  • If a matching case is found, the code for that case is executed, and all subsequent cases are also executed unless a break statement is encountered.
  • If no matching case is found, the code for the optional default case is executed.
  • The switch statement can only compare integers, characters, and enumerated types.

Summary

The switch statement in C is a powerful control flow statement that allows a program to execute code based on the value of an expression. It offers an efficient and straightforward alternative to the if-else-if ladder for multiple conditions. Understanding the syntax, use cases, and important points for the switch statement is crucial for writing effective C programs.

Published on: