π― Comprehensive Analysis of the C Language switch Statement: The Clearest Multi-Branch Selection Structure
π§ Why Use switch?
If we let users choose a function:
1. Start Game
2. View Help
3. Exit System
If using if statements π
if(x==1)...
else if(x==2)...
else if(x==3)...
else...
Although it can be written, it is too long, hard to read, and not elegant β
To make the code structure clear and the logic straightforward, C language provides π½ β the switch multi-branch selection structure
β¨ I. Basic Syntax of switch (The Most Important Structure)
switch (expression) {
case constant1:
statement;
break;
case constant2:
statement;
break;
...
default:
statement;
}
π Rules to Remember
| Rule | Description |
|---|---|
| The expression must be an integer or character | β
<span>int</span> β
<span>char</span> β <span>float</span> |
| case must be a constant | Numbers, characters, enumerations |
| break is used to stop further execution | No break β will continue executing downwards |
| default is optional but recommended | To handle invalid input |
π II. Super Basic Example of switch: Function Menu
π Practical Application: System menus, unattended device control, etc.
#include <stdio.h>
int main() {
int choice;
printf("=== Welcome to the System ===\n");
printf("1. Log in to the system\n");
printf("2. View Help\n");
printf("3. Exit System\n");
printf("Please enter your choice:");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Login successful!\n");
break;
case 2:
printf("Help: Please contact the administrator if you have any questions.\n");
break;
case 3:
printf("System has exited.\n");
break;
default:
printf("Invalid input, please reselect!\n");
}
return 0;
}
Example of Running Effect:
Please enter your choice: 2
Help: Please contact the administrator if you have any questions.
β The framework is very clear!
π III. switch and case Merge Technique (Multiple Conditions with Same Result)
π Scenario: Month β Season (The Most Classic Example)
#include <stdio.h>
int main() {
int month;
printf("Please enter the month (1-12):");
scanf("%d", &month);
switch(month) {
case 3: case 4: case 5:
printf("πΈSpring\n"); break;
case 6: case 7: case 8:
printf("βοΈSummer\n"); break;
case 9: case 10: case 11:
printf("πAutumn\n"); break;
case 12: case 1: case 2:
printf("βοΈWinter\n"); break;
default:
printf("Invalid month!\n");
}
return 0;
}
β Merging multiple conditions β one of the greatest advantages of switch!
π€ IV. switch Handling Character Branches (Very Practical)
π Scenario: Keyboard commands, menu shortcuts
#include <stdio.h>
int main() {
char op;
printf("Enter command (R=Read W=Write Q=Quit):");
scanf(" %c", &op); // Add space to prevent interference from newline
switch(op) {
case 'R':
printf("Executing read operation...\n"); break;
case 'W':
printf("Executing write operation...\n"); break;
case 'Q':
printf("Program exiting...\n"); break;
default:
printf("Invalid command!\n");
}
return 0;
}
π Commonly used in program command menus β
π§ͺ V. What Happens Without break? (Must Master)
#include <stdio.h>
int main() {
int a = 2;
switch(a) {
case 1: printf("One ");
case 2: printf("Two ");
case 3: printf("Three ");
}
return 0;
}
Output:
Two Three
β οΈ Explanation: Matched case 2, then continues executing until the end β fall-through mechanism In most cases, we must add break β
π― VI. Super Practical: Simple Calculator
π Input: Number Operator Number π Output: Calculation Result π Error Handling Complete
#include <stdio.h>
int main() {
float a, b;
char op;
printf("Please enter the expression (e.g., 8 * 2):");
scanf("%f %c %f", &a, &op, &b);
switch(op) {
case '+': printf("Result = %.2f\n", a + b); break;
case '-': printf("Result = %.2f\n", a - b); break;
case '*': printf("Result = %.2f\n", a * b); break;
case '/':
if(b == 0)
printf("Error! Divisor cannot be 0!\n");
else
printf("Result = %.2f\n", a / b);
break;
default:
printf("Invalid operator!\n");
}
return 0;
}
β Highly practical β Recommended for classroom experiments
π VII. Summary of Differences Between switch and if
| Scenario | Recommended Use |
|---|---|
| Complex layered condition judgment | if |
| Range judgment (e.g., greater than XX) | if |
| Choosing one branch from multiple fixed values | β switch |
| Menu / Command Control | β switch |
| Many mutually exclusive conditions | β switch |
π§ Mnemonic
Use switch for fixed options, use if for continuous ranges
π VIII. Classroom Exercises (Three Must-Do + Complete Code)
β Exercise 1: Convert number to week (1~7)
β Exercise 2: Input letter (A~F) to output quality level
β Exercise 3: Input exam scores, convert to 5-point grading system (90+ A; 80~89 B; 70~79 C; 60~69 D; <60 E)
π Answer codes in the next issue
β Summary of This Section
| Skills Mastered | Evaluation |
|---|---|
| Basic syntax of switch | β |
| Function of break | β |
| Merging multiple cases | β |
| Character judgment | β |
| Choosing application scenarios | β |
| Preventing fall-through mechanism | β |
β Program decision-making ability has improved! Next step: Allow the program torepeat tasks π
π Next Section Preview
Strong Explanation of C Language Loop Structures (for/while/do-while)
- Multiplication Table β
- Sum Calculation β
- Input Student Scores Until End β
- Console Animation β
π IoT Smart Classroom
Continuously updated: #C Language Basics #IoT Training #Project-Based Teaching Follow me, and let’s master programming from 0 to 1 together!π₯