C Switch Statement

Multi-way branching in C programming

What is a Switch Statement?

Definition: The switch statement is a multi-way branch statement that tests a variable against a list of values (cases). It provides an alternative to multiple if-else statements when comparing a single variable against several constant values.

Basic Syntax

switch (expression) { case constant1: // code block break; case constant2: // code block break; default: // code block }

Simple 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; case 6: printf("Saturday\n"); break; case 7: printf("Sunday\n"); break; default: printf("Invalid day\n"); } return 0; } // Output: Wednesday

The Break Statement

Important: The break statement is crucial! Without it, execution will "fall through" to the next case.
// WITHOUT break (fall-through behavior) int grade = 'B'; switch (grade) { case 'A': printf("Excellent!\n"); case 'B': printf("Good!\n"); case 'C': printf("Fair!\n"); default: printf("Done\n"); } // Output: Good! // Fair! // Done // WITH break (correct behavior) switch (grade) { case 'A': printf("Excellent!\n"); break; case 'B': printf("Good!\n"); break; case 'C': printf("Fair!\n"); break; default: printf("Done\n"); } // Output: Good!

The Default Case

Note: The default case is optional but recommended. It handles all values not explicitly covered by case statements.
int choice = 9; switch (choice) { case 1: printf("Option 1\n"); break; case 2: printf("Option 2\n"); break; default: printf("Invalid option\n"); break; // break is optional in default }

Multiple Cases for Same Action

char ch = 'e'; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': printf("%c is a vowel\n", ch); break; default: printf("%c is a consonant\n", ch); } // Output: e is a vowel

Nested Switch Statements

int category = 1; int subcategory = 2; switch (category) { case 1: printf("Category 1\n"); switch (subcategory) { case 1: printf(" Subcategory 1\n"); break; case 2: printf(" Subcategory 2\n"); break; } break; case 2: printf("Category 2\n"); break; }

Practical Examples

Example 1: Simple Calculator

#include <stdio.h> int main() { char operator; double num1, num2, result; printf("Enter operator (+, -, *, /): "); scanf("%c", &operator); printf("Enter two numbers: "); scanf("%lf %lf", &num1, &num2); switch (operator) { case '+': result = num1 + num2; printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result); break; case '-': result = num1 - num2; printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result); break; case '*': result = num1 * num2; printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result); break; case '/': if (num2 != 0) { result = num1 / num2; printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result); } else { printf("Error: Division by zero\n"); } break; default: printf("Error: Invalid operator\n"); } return 0; }

Example 2: Menu System

#include <stdio.h> int main() { int choice; printf("=== Menu ===\n"); printf("1. New File\n"); printf("2. Open File\n"); printf("3. Save File\n"); printf("4. Exit\n"); printf("Enter choice: "); scanf("%d", &choice); switch (choice) { case 1: printf("Creating new file...\n"); break; case 2: printf("Opening file...\n"); break; case 3: printf("Saving file...\n"); break; case 4: printf("Exiting...\n"); break; default: printf("Invalid choice!\n"); } return 0; }

Example 3: Month Days

#include <stdio.h> int main() { int month = 2; int year = 2024; int days; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 4: case 6: case 9: case 11: days = 30; break; case 2: if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) days = 29; // Leap year else days = 28; break; default: printf("Invalid month\n"); return 1; } printf("Days in month %d: %d\n", month, days); return 0; }

Switch vs If-Else

Feature Switch If-Else
Expression Type Integer, char, enum only Any boolean expression
Equality Check Only equality (==) Any comparison (<, >, ==, etc.)
Performance Faster for many cases Slower for many conditions
Readability Better for multiple values Better for complex conditions
Default Case default keyword final else

Limitations and Rules

Important Limitations:
  • Expression must be of integer or character type
  • Case values must be constant expressions (compile-time constants)
  • Cannot use variables or ranges in case labels
  • Each case value must be unique
  • Cannot use floating-point values
// INVALID examples int x = 5; switch (x) { case x: // ERROR: case must be constant break; case 1...5: // ERROR: ranges not allowed in C break; } double d = 3.14; switch (d) { // ERROR: float/double not allowed case 3.14: break; }

Best Practices

Recommendations:
  • Always use break unless fall-through is intentional
  • Include a default case for error handling
  • Keep case blocks short and simple
  • Use braces { } for multi-statement cases
  • Comment intentional fall-through cases
  • Consider using enums for better readability
  • Use switch for equality checks, if-else for ranges

Key Takeaways

Remember:
  • Switch tests a single variable against multiple constant values
  • Always use break to prevent fall-through
  • Only works with integers, characters, and enums
  • Case values must be compile-time constants
  • default case handles unmatched values
  • More efficient than multiple if-else for many cases