Comprehensive Analysis of the C Language switch Statement: The Clearest Multi-Branch Selection Structure

🎯 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!πŸ”₯

Leave a Comment