Skip to content

Module 3 · Decisions and Loops — topic 2 of 5

The switch Statement

switch selects one of many branches by comparing an integer expression with constant case labels. Learn case, default, break, intentional fall-through and when switch beats an else-if ladder.

Beginner 13 min read·Lesson 12 of 37 in C Programming

Learning objectives

  • Write switch statements with case, default and break
  • Explain and deliberately use fall-through
  • Choose between switch and if-else

Definition

A switch statement transfers control to the case label whose integer constant expression equals the value of the controlling expression, or to default if none match; execution continues until a break or the end of the switch body.

Introduction

Menu-driven programs — “1. Deposit 2. Withdraw 3. Exit” — compare one value against many fixed options. Writing that as an else-if ladder works, but switch expresses the intent more clearly and can compile to a fast jump table.

switch has one surprising rule: after a matching case runs, execution falls through into the next case unless you write break.

Why it matters

Forgotten breaks are a classic exam question and a real source of bugs. Understanding fall-through lets you avoid it — or use it deliberately to group cases.

Command dispatch, state machines and protocol parsers in C are usually written with switch.

Detailed explanation

The controlling expression must have an integer type (int, char, an enum, …). Floating-point values and strings cannot be switched on.

Each case label must be an integer constant expression — a literal, character constant, enumeration constant or macro — and no two labels may be equal.

Control jumps to the matching label and runs statements from there downward. break exits the switch. If there is no break, execution continues into the next label's statements: this is fall-through.

default runs when no case matches. It may appear anywhere but is conventionally last; include it to handle unexpected values.

Use switch whenUse if-else when
Comparing one integer with fixed valuesTesting ranges (marks >= 90)
Values are constants known at compile timeConditions involve several variables
Many options of equal standingComparing floats or strings

Syntax

C
switch (expression) {
case CONSTANT_1:
/* statements */
break;
case CONSTANT_2:
case CONSTANT_3: /* shared code for 2 and 3 */
/* statements */
break;
default:
/* no case matched */
break;
}
  • Case labels end with a colon, not a semicolon.
  • Stacking labels without statements shares one branch.
  • Declare variables inside a case within braces { } to give them their own scope.

Code examples

Day of the week

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;
default: printf("Another day\n"); break;
}
return 0;
}
Output
Wednesday

Fall-through when break is missing

C
#include <stdio.h>
int main(void) {
int level = 2;
switch (level) {
case 1: printf("one ");
case 2: printf("two ");
case 3: printf("three ");
default: printf("done\n");
}
return 0;
}
Output
two three done

Execution starts at case 2 and runs every statement below it.

More examples

A calculator using char cases and grouped labels

C
#include <stdio.h>
double apply(double a, char op, double b, int *ok) {
*ok = 1;
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*':
case 'x':
case 'X': return a * b; /* three symbols, one branch */
case '/':
if (b != 0) return a / b;
/* fall through to the error */
default:
*ok = 0;
return 0;
}
}
int main(void) {
char ops[] = {'+', 'x', '/', '/', '%'};
double rhs[] = {4, 4, 4, 0, 4};
for (int i = 0; i < 5; i++) {
int ok;
double r = apply(10, ops[i], rhs[i], &ok);
if (ok) printf("10 %c %g = %g\n", ops[i], rhs[i], r);
else printf("10 %c %g: invalid\n", ops[i], rhs[i]);
}
return 0;
}
Output
10 + 4 = 14
10 x 4 = 40
10 / 4 = 2.5
10 / 0: invalid
10 % 4: invalid

Step-by-step explanation

  • switch (op) works because a char is an integer type; '+' is a character constant.
  • return leaves the function, so those cases need no break.
  • '*', 'x' and 'X' are stacked labels that share the multiplication branch.
  • For '/' with a zero divisor the if is false and execution deliberately falls into default.
  • '%' matches no case, so default reports it as invalid. %g prints numbers without trailing zeros.

Expected output

Running “A calculator using char cases and grouped labels” prints exactly:

TextOutput
10 + 4 = 14
10 x 4 = 40
10 / 4 = 2.5
10 / 0: invalid
10 % 4: invalid

Practical applications

  • Menu-driven console applications dispatch on the user's choice.
  • Interpreters and virtual machines switch on opcode values.
  • Embedded state machines switch on an enum state.

Best practices

  • Put a break at the end of every case, including the last one.
  • Mark intentional fall-through with a comment such as /* fall through */.
  • Always include a default case to catch unexpected values.

Common mistakes

Forgetting break

Avoid

case 1: printf("Deposit\n");
case 2: printf("Withdraw\n"); break;

Prefer

case 1: printf("Deposit\n"); break;
case 2: printf("Withdraw\n"); break;

Choosing 1 prints both lines because control falls into case 2.

Using a range or variable as a label

Avoid

case marks >= 90: /* ... */

Prefer

if (marks >= 90) { /* ... */ }

Case labels must be integer constant expressions; ranges belong in if statements.

Switching on a string

Avoid

switch (command) { case "quit": /* ... */ }

Prefer

if (strcmp(command, "quit") == 0) { /* ... */ }

Strings are arrays, not integers. Compare them with strcmp.

Important notes

  • C23 adds the [[fallthrough]]; attribute to mark intentional fall-through; GCC's -Wimplicit-fallthrough warns about unmarked fall-through.
  • Jumping past a variable's initialisation into its scope is not allowed for variable-length arrays; wrap case-local variables in braces.

Key takeaways

  • switch compares an integer expression with constant case labels.
  • Without break, execution falls through to the next case.
  • Use default for unmatched values and if for ranges or strings.

Try it yourself

  1. 1
    Write a menu program: read 1–4 and print “Add”, “Search”, “Delete” or “Exit”, with an error for anything else.
  2. 2
    Read a character and use grouped cases to print whether it is a vowel or a consonant (handle upper and lower case).

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhich type can NOT be used as a switch expression?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this topic