Skip to main content

C Switch Statement

The switch statement is a multi-way decision-making control structure that tests whether an expression matches one of several constant integer values and branches accordingly. It provides an elegant alternative to long chains of if-else statements when comparing a variable against multiple discrete values.

mdx
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

Basic Syntax

The general syntax of a switch statement in C is:

c
switch (expression) {
case constant1:
// code to be executed if expression equals constant1
break;
case constant2:
// code to be executed if expression equals constant2
break;
...
default:
// code to be executed if expression doesn't match any case
break;
}

How Switch Statement Works

  1. The expression is evaluated once
  2. The value of the expression is compared with the values of each case
  3. If there's a match, the corresponding block of code is executed
  4. The break statement is used to terminate the switch case and exit the switch block
  5. If no match is found, the default statement is executed (if provided)

Key Features

  • The expression in a switch must evaluate to an integral type (int, char, short, etc.)
  • Floating-point expressions are not allowed
  • The values in case statements must be constant expressions (literals or constants)
  • The default statement is optional
  • The break statement is typically needed after each case (except sometimes the last one)

Example: Simple Switch Statement

Here's a basic example of a switch statement that prints different messages based on a grade:

c
#include <stdio.h>

int main() {
char grade = 'B';

switch (grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Well done!\n");
break;
case 'C':
printf("Good job!\n");
break;
case 'D':
printf("You passed, but could do better.\n");
break;
case 'F':
printf("You failed. Try again.\n");
break;
default:
printf("Invalid grade.\n");
break;
}

return 0;
}

The output of this program will be:

Well done!

Falling Through - Omitting the break Statement

If you omit the break statement, execution will "fall through" to the next case, regardless of whether the next case's value matches the expression. This can be useful when you want multiple cases to execute the same code.

c
#include <stdio.h>

int main() {
int day = 3;

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
printf("It's a weekday.\n");
break;
case 6:
case 7:
printf("It's the weekend!\n");
break;
default:
printf("Invalid day number.\n");
break;
}

return 0;
}

In this example, any value of day from 1 to 5 will print "It's a weekday."

Nested Switch Statements

Switch statements can be nested inside other switch statements:

c
#include <stdio.h>

int main() {
int department = 1;
int position = 2;

switch (department) {
case 1: // IT Department
printf("IT Department: ");
switch (position) {
case 1:
printf("Manager\n");
break;
case 2:
printf("Developer\n");
break;
default:
printf("Other role\n");
break;
}
break;
case 2: // HR Department
printf("HR Department: ");
switch (position) {
case 1:
printf("Director\n");
break;
case 2:
printf("Recruiter\n");
break;
default:
printf("Other role\n");
break;
}
break;
default:
printf("Unknown department\n");
break;
}

return 0;
}

This program will output: IT Department: Developer

Switch vs. If-Else

c
switch (choice) {
case 1:
printf("Option 1 selected\n");
break;
case 2:
printf("Option 2 selected\n");
break;
case 3:
printf("Option 3 selected\n");
break;
default:
printf("Invalid option\n");
break;
}

When to Use Switch vs. If-Else

  • Use switch when:

    • Comparing a single variable against multiple constant values
    • You have several (more than 2-3) alternative paths based on the same variable
    • All comparisons are for equality (not ranges or other conditions)
  • Use if-else when:

    • Testing multiple conditions
    • Testing ranges of values
    • Comparing different variables
    • Using non-integral types (like floating-point)
    • Using complex expressions or conditions

Common Pitfalls

  1. Forgetting break statements:

    • Without break, execution "falls through" to the next case
    • This is usually not intended and can cause logical errors
  2. Non-constant case values:

    • Case values must be compile-time constants
    • Variables cannot be used for case values
  3. Duplicate case values:

    • Having the same value for multiple cases causes compilation errors
  4. Non-integral expression:

    • The switch expression must have an integral type (int, char, etc.)
    • Floating-point values are not allowed

Practice Exercise

Write a switch statement that takes a month number (1-12) and prints the number of days in that month. Consider leap years for February (assume it's not a leap year for simplicity).

Solution
c
#include <stdio.h>

int main() {
int month = 4; // April

switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
printf("31 days\n");
break;
case 4: case 6: case 9: case 11:
printf("30 days\n");
break;
case 2:
printf("28 days (29 in leap years)\n");
break;
default:
printf("Invalid month\n");
break;
}

return 0;
}

Output: 30 days

Conclusion

The switch statement is a powerful control structure in C for handling multi-way branching based on a single expression. While it has some limitations (such as requiring integral types and constant case values), it provides cleaner and more efficient code compared to long if-else chains when comparing a single variable against multiple discrete values.

When used appropriately with proper break statements, switch statements can make your code more readable and maintainable. Understanding when to use switch versus if-else is an important skill for writing clean and efficient C code.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)