How to Use Switch Case in C: Syntax and Examples
In C, use the
switch statement to select one of many code blocks to execute based on a variable's value. Each case defines a value to match, and break ends the case to prevent fall-through. The default case runs if no other case matches.Syntax
The switch statement evaluates an expression and executes the matching case block. Use break to stop execution after a case. The default case runs if no other case matches.
- switch(expression): The value to check.
- case value: Code to run if expression equals value.
- break; Stops running more cases.
- default: Runs if no case matches.
c
switch (expression) { case value1: // code to run if expression == value1 break; case value2: // code to run if expression == value2 break; // more cases... default: // code to run if no case matches break; }
Example
This example shows how to use switch to print a message based on a number from 1 to 3. If the number is not 1, 2, or 3, it prints a default message.
c
#include <stdio.h> int main() { int number = 2; switch (number) { case 1: printf("Number is one\n"); break; case 2: printf("Number is two\n"); break; case 3: printf("Number is three\n"); break; default: printf("Number is not 1, 2, or 3\n"); break; } return 0; }
Output
Number is two
Common Pitfalls
Common mistakes include forgetting break statements, which causes "fall-through" where multiple cases run unintentionally. Also, switch only works with integral types (like int or char), not floating-point or strings.
Example of missing break causing fall-through:
c
#include <stdio.h> int main() { int day = 2; switch (day) { case 1: printf("Monday\n"); case 2: printf("Tuesday\n"); case 3: printf("Wednesday\n"); break; default: printf("Other day\n"); break; } return 0; } /* Output: Tuesday Wednesday */
Output
Tuesday
Wednesday
Quick Reference
- Use
switchfor clear multi-choice branching. - Always add
breakto avoid fall-through unless intentional. defaultis optional but recommended for unexpected values.switchworks withint,char, and enums only.
Key Takeaways
Use
switch to select code blocks based on a variable's value.Always include
break after each case to prevent running multiple cases.The
default case handles values not matched by any case.Switch works only with integral types like int and char, not strings or floats.
Missing breaks cause fall-through, which can lead to unexpected behavior.