Back to Blog

C in 100 Seconds: Switch Statement | Episode 6

Daryl WongDaryl Wong

Video: C in 100 Seconds: Switch — case, break, default | Episode 6 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Switch — Clean Multi-Way Branching in C

C in 100 Seconds, Episode 6


When you're comparing one variable against several specific values, a chain of if/else if statements gets tedious. switch gives you a cleaner structure.

The Switch Statement

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("Other day\n");
}

C jumps directly to the matching case label and executes from there.

The Break Is Critical

Without break, execution falls through to the next case. This is intentional in C's design — sometimes you want multiple cases to share the same code. But most of the time, forgetting break is a bug.

Default

The default label catches anything that doesn't match a case. It's like the else at the end of an if-chain. It's optional, but good practice to include it.

When to Use Switch vs If

Use switch when you're comparing a single integer or char against known constant values. Use if/else when your conditions involve ranges, multiple variables, or floating-point comparisons.

Full Code

#include <stdio.h>

int main() {
  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("Other day\n");
  }

  return 0;
}

Compile and Run

gcc switch.c -o switch
./switch

Next episode: While Loops — repeating code until a condition changes.

Student code: github.com/GoCelesteAI/c-in-100-seconds/episode06