switch...case in C Programming

Switch statements in C programming provide a way to select one of several code blocks for execution based on the value of an expression or variable. They are particularly useful when you have multiple cases to consider.

switch...case

Syntax:
switch (expression) { case constant1: // Code to execute if expression matches constant1 break; case constant2: // Code to execute if expression matches constant2 break; // More cases can follow default: // Code to execute if no cases match }
  1. expression: is the value that you want to compare against different constants (integer or character constants).
  2. case constant: defines a specific value or constant that expression is compared against.
  3. break statement: is used to exit the switch statement once a match is found.
  4. default: is an optional case that executes if none of the other cases match.

The expression is evaluated first. The value of the expression is compared to each of the case values. If the value of the expression matches a case value, the block of statements associated with that case is executed. The break statement is used to terminate the switch statement. If the value of the expression does not match any of the case values, the default block of statements is executed.

Switch...case Example

#include <stdio.h> int main() { int day = 3; switch (day) { case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; case 3: printf("Wednesday\n"); break; case 4: printf("Thursday\n"); break; case 5: printf("Friday\n"); break; default: printf("Weekend\n"); } return 0; }

In this example, the value of the day variable (3) is compared to various cases. Since day matches the value of 3, the code under case 3: executes, and "Wednesday" is printed. The break statement ensures that the switch statement exits after the matching case.

Note: It's crucial to use break statements in each case to prevent "fall-through," where execution continues to the next case even after a match. The default case is executed when none of the other cases match.

Conclusion

Switch statements are efficient for situations where you need to select one of many possible code blocks based on the value of a single expression. They make the code more concise and readable than using a series of if-else if statements.