Skip to content

Switch statement in C

The switch statement in C is a control flow statement that allows a program to evaluate an expression and execute different blocks of code based on the value of that expression. It provides an alternative to using multiple if-else statements when testing a single variable against multiple values. The switch statement enhances code readability and can lead to more efficient code execution, especially when dealing with a large number of cases.

Syntax:

switch (expression)

 {

case constant1:

// Code block to execute if expression == constant1

break;

case constant2:

// Code block to execute if expression == constant2

break;

// Add more case statements as needed

default:

 // Code block to execute if expression does not match any case

}

Explanation:

  • The switch keyword marks the beginning of the switch statement, followed by the expression in parentheses. This expression is evaluated to determine which case to execute.
  • Inside the switch block, one or more case labels are defined using the case keyword, followed by a constant value (integer, character, or enumerated type). If the expression matches the value of a case label, the corresponding block of code is executed.
  • The break statement is used to terminate the switch block. If a break statement is not included after a case block, execution will continue to the next case block, resulting in fall-through behavior.
  • The default case is optional and is executed if the expression does not match any of the defined case labels. It serves as a catch-all case and is commonly used for error handling or handling unexpected input.

Example:

#include <stdio.h>

 int main()

 {

int choice;

 printf(“Choose an option (1, 2, or 3): “);

scanf(“%d”, &choice);

switch (choice)

 {

 case 1: printf(“You chose option 1.\n”); break;

case 2: printf(“You chose option 2.\n”); break;

case 3: printf(“You chose option 3.\n”); break;

default: printf(“Invalid choice. Please choose 1, 2, or 3.\n”);

 }

return 0;

}

Explanation of Example:

  • The program prompts the user to input a choice (1, 2, or 3).
  • The switch statement evaluates the value of choice and executes the corresponding case block.
  • If the value of choice matches 1, 2, or 3, the respective printf statement is executed.
  • If the value of choice does not match any of the defined case labels, the default case is executed, displaying an error message.

Notes:

  • Each case label must be a constant expression, and the constants must be unique within the switch block.
  • The break statement is important to prevent fall-through behavior. If a break statement is omitted, execution will continue to the next case label, resulting in unintended behavior.
  • The switch statement is primarily used for comparing integral types (int, char) and enumerated types. It does not support floating-point types or strings.