Mastering the C Switch Statement: Syntax, Flow, and Practical Example
Mastering the C Switch Statement
In this tutorial you’ll discover how to craft a clean, efficient switch statement in C, complete with a hands‑on calculator example.
The switch construct lets you execute one block of code out of many alternatives. While you could use an if…else if chain, switch delivers clearer syntax and faster readability, especially when the decision hinges on a single expression.
Switch‑Case Syntax
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
/* … */
default:
// default statements
}
How it works
- The expression is evaluated once and compared against each case label.
- When a match is found, the corresponding block runs until a
break(or end of theswitch) is reached. - If no match occurs, the optional
defaultblock executes.
Key points
- Omitting
breakcauses fall‑through: subsequent cases run as well. - The
defaultclause is optional but highly recommended for error handling.
Switch Statement Flowchart

Example: Simple Calculator
#include <stdio.h>
int main(void) {
char operation;
double n1, n2;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operation);
printf("Enter two operands: ");
scanf("%lf %lf", &n1, &n2);
switch (operation) {
case '+':
printf("%.1lf + %.1lf = %.1lf\\n", n1, n2, n1 + n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf\\n", n1, n2, n1 - n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf\\n", n1, n2, n1 * n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf\\n", n1, n2, n1 / n2);
break;
default:
printf("Error! operator is not correct\\n");
}
return 0;
}
Output example
Enter an operator (+, -, *, /): - Enter two operands: 32.5 12.4 32.5 - 12.4 = 20.1
When the user inputs -, the program jumps to the corresponding case, performs the subtraction, and the break exits the switch. If the operator is invalid, the default clause alerts the user.
C Language
- Mastering the C# Switch Statement: Syntax, Examples & Best Practices
- C# Break Statement: How & When to Use It
- Mastering the C# Continue Statement: How to Skip Loop Iterations Effectively
- Mastering the C++ Switch‑Case Statement: Syntax, Workflow, and Practical Examples
- Mastering C Conditional Statements: If, Else, and More
- Mastering the Java Switch Statement: Syntax, Usage, and Best Practices
- Mastering VHDL Generate Statements: Build Reusable Debouncers with Ease
- Mastering C++ Switch‑Case: Syntax, Usage, and Practical Examples
- Understanding Switch‑Case in C: Syntax, Examples, and Best Practices
- Java Switch‑Case Statement Explained: Syntax, Examples, and Best Practices