Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

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

Key points


Switch Statement Flowchart

Mastering the C Switch Statement: Syntax, Flow, and Practical Example

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

  1. Mastering the C# Switch Statement: Syntax, Examples & Best Practices
  2. C# Break Statement: How & When to Use It
  3. Mastering the C# Continue Statement: How to Skip Loop Iterations Effectively
  4. Mastering the C++ Switch‑Case Statement: Syntax, Workflow, and Practical Examples
  5. Mastering C Conditional Statements: If, Else, and More
  6. Mastering the Java Switch Statement: Syntax, Usage, and Best Practices
  7. Mastering VHDL Generate Statements: Build Reusable Debouncers with Ease
  8. Mastering C++ Switch‑Case: Syntax, Usage, and Practical Examples
  9. Understanding Switch‑Case in C: Syntax, Examples, and Best Practices
  10. Java Switch‑Case Statement Explained: Syntax, Examples, and Best Practices