C switch Statement

Beginner
⏱️ 13 min read
📚 Updated: Jul 2026
🎯 5 Examples
Multi-way branch

What You’ll Learn

The switch statement picks one branch from many based on a single integer value—menu options, day numbers, letter grades. You label each path with case, exit with break, and handle surprises with default. This tutorial covers syntax, fall-through, five examples, and when switch beats a long else if chain.

01

case

Labels.

02

break

Exit.

03

default

Fallback.

04

Fall-through

No break.

05

int/char

Only ints.

06

else if

Alt tool.

Definition and Usage

A switch statement evaluates an expression once and jumps to the matching case label. Each case must be a compile-time integer constant (1, 'A', ENUM_VALUE). If no case matches, default runs when present.

Use switch when one variable is compared to several fixed values. For score ranges or complex conditions, prefer else if or nested if instead.

💡
Beginner Tip

Put break; at the end of every case unless you intentionally want fall-through. Missing break is one of the most common switch bugs in beginner C code.

📝 Syntax

General form of a switch with case, break, and default:

C
switch (expression) {
    case value1:
        // statements for value1
        break;
    case value2:
        // statements for value2
        break;
    default:
        // when no case matches
        break;
}

Parts explained

  • switch (expression) — evaluated once; must be integer type.
  • case value: — if expression equals value, execution starts here.
  • break; — jumps out of the entire switch block.
  • default: — optional catch-all when nothing matches.

Compile

C
gcc program.c -std=c11 -o program

⚡ Quick Reference

PatternExample
Integer menuswitch (choice) { case 1: ... break; }
char gradecase 'A': ... case 'B': ...
default guarddefault: printf("Invalid\n"); break;
Grouped casescase 6: case 7: printf("Weekend\n"); break;
Not allowedswitch (x) case 1.5: — no float cases
break
exit switch

Stop fall-through

default
optional

Catch unknown

case
constants

int / char / enum

fall-through
no break

Runs next case

Examples Gallery

Compile with gcc example.c -std=c11 -o example. Each program demonstrates a different switch pattern.

📚 Getting Started

Basic switch with case, break, and default from the reference material.

Example 1 — Day of the Week

Map integers 1–7 to weekday names.

C
#include <stdio.h>

int main(void) {
    int day = 3;

    switch (day) {
        case 1:
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;
        case 4:
            printf("Thursday\n");
            break;
        case 5:
            printf("Friday\n");
            break;
        case 6:
            printf("Saturday\n");
            break;
        case 7:
            printf("Sunday\n");
            break;
        default:
            printf("Invalid day\n");
    }

    return 0;
}

How It Works

day is 3, so execution jumps to case 3:, prints Wednesday, then break exits the switch. Cases 4–7 and default are skipped.

Example 2 — Letter Grade with char

switch works with character constants like 'A'.

C
#include <stdio.h>

int main(void) {
    char grade = 'B';

    switch (grade) {
        case 'A':
            printf("Excellent!\n");
            break;
        case 'B':
            printf("Well done\n");
            break;
        case 'C':
            printf("Good\n");
            break;
        case 'D':
            printf("You passed\n");
            break;
        case 'F':
            printf("Better try again\n");
            break;
        default:
            printf("Invalid grade\n");
    }

    return 0;
}

How It Works

char promotes to int in C, so grade == 'B' matches case 'B':. default catches typos like 'X'.

📈 Practical Patterns

Fall-through, menus, and grouped cases.

Example 3 — Unintentional Fall-through

Without break, execution continues into the next cases.

C
#include <stdio.h>

int main(void) {
    int number = 2;

    switch (number) {
        case 1:
            printf("One\n");
        case 2:
            printf("Two\n");
        case 3:
            printf("Three\n");
        default:
            printf("Default\n");
    }

    return 0;
}

How It Works

Matching case 2: runs, but with no break C falls through into case 3 and default. This is usually a bug—add break; after each case unless grouping on purpose.

Example 4 — Simple Calculator Menu

Route operator choice to add, subtract, multiply, or divide.

C
#include <stdio.h>

int main(void) {
    int op = 2;
    double a = 10.0, b = 4.0, result;

    switch (op) {
        case 1:
            result = a + b;
            printf("%.2f + %.2f = %.2f\n", a, b, result);
            break;
        case 2:
            result = a - b;
            printf("%.2f - %.2f = %.2f\n", a, b, result);
            break;
        case 3:
            result = a * b;
            printf("%.2f * %.2f = %.2f\n", a, b, result);
            break;
        case 4:
            if (b != 0.0) {
                result = a / b;
                printf("%.2f / %.2f = %.2f\n", a, b, result);
            } else {
                printf("Cannot divide by zero\n");
            }
            break;
        default:
            printf("Unknown operator %d\n", op);
    }

    return 0;
}

How It Works

The switch selects the operation; math uses double inside each case. Keep case bodies simple—complex logic can call a helper function instead.

Example 5 — Intentional Grouped Cases

Stack cases without break between them to share one block.

C
#include <stdio.h>

int main(void) {
    int day = 6;

    switch (day) {
        case 6:
        case 7:
            printf("Weekend\n");
            break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            printf("Weekday\n");
            break;
        default:
            printf("Invalid day\n");
    }

    return 0;
}

How It Works

case 6: has no body—execution falls through to case 7:, then both share the “Weekend” message. This is the good use of fall-through.

🚀 Common Use Cases

  • Menus — route 1, 2, 3 to different actions.
  • State machines — jump on discrete status codes.
  • Token parsers — handle character or opcode values.
  • Day/month enums — map constants to labels.
  • Error codes — print messages per error number.
  • Keyboard input — WASD or arrow-key handling in games.

🧠 How switch Works

1

Evaluate expression

Compute the switch value once (e.g. day = 3).

Start
2

Find matching case

Jump to the first case label that equals the value.

Match
3

Run case body

Execute statements until break or end of switch.

Execute
=

break or fall-through

break exits; no break runs the next case. No match → default.

📝 Notes

  • Case labels must be integer constants—not variables or ranges.
  • You cannot switch on float, double, or strings.
  • Always add break; unless fall-through is intentional.
  • Include default for invalid or unexpected values.
  • Duplicate case values in one switch are a compile error.
  • Variables declared inside a case may need an extra { } block in C.

⚡ Optimization

Compilers often turn dense switch statements into jump tables for fast dispatch. Sparse or huge case sets may still use comparisons. For a handful of menu options, readability matters more than micro-optimization. If every case runs similar code, extract a function and call it from each case.

Conclusion

The switch statement is C’s clean way to branch on one integer value against many constants. Master case, break, and default, understand fall-through, and you will write clearer menu and dispatch code than a long else if chain.

Next, dive deeper into break—it exits loops as well as switch blocks.

💡 Best Practices

✅ Do

  • End every case with break; unless grouping
  • Always provide a default branch
  • Keep case bodies short; call functions for heavy logic
  • Use grouped cases for shared behavior (weekend, seasons)
  • Comment intentional fall-through so readers know it is on purpose

❌ Don’t

  • Forget break and accidentally run multiple cases
  • Use switch for range checks like score >= 80
  • Switch on floating-point values (not allowed in C)
  • Declare variables in a case without wrapping in { }
  • Duplicate the same code in every case without a helper

Key Takeaways

Knowledge Unlocked

Five things to remember about switch

Multi-way branching in C.

5
Core concepts
02

break

Exit switch.

Flow
🔢 03

default

Fallback.

Safety
📝 04

Fall-through

No break.

Caution
📈 05

int only

No float.

Types

❓ Frequently Asked Questions

switch compares one integer expression against labeled case values. When a case matches, its statements run until break or the end of the switch. An optional default handles no match.
The switch expression and case labels must be integer types: int, char, short, long, or enum. C does not allow switch on float, double, or strings. Compare strings with if-else or strcmp.
break exits the switch block immediately. Without break, execution falls through into the next case. Always use break unless you deliberately want fall-through.
Fall-through happens when a case has no break and execution continues into the following case(s). It can be a bug or intentional—e.g. grouping case 6 and case 7 for weekend.
Use switch when comparing one variable to many constant values (menu 1/2/3, day 1-7). Use else if for ranges (score >= 80) or unrelated conditions.
No, but include default to catch unexpected input. It improves robustness and makes debugging easier when a value does not match any case.
Did you know?

In C, else if is really else { if ... } nested inside another branch. Similarly, each case in a switch is just a label—execution does not automatically stop at the next case unless you write break;. That design is why fall-through exists at all.

Continue to break

Learn how break exits loops and switch cases cleanly.

break tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful