🎓 A1Learner
🔍
0 of 50 lessons completed

C Switch

If else chose between two blocks. A switch statement chooses one block from a list by matching a value, and each block starts with the word case.

One matching case

This program sets day to 2. The case for 2 matches, so its line prints.

#include <stdio.h>

int main() {
  int day = 2;
  switch (day) {
    case 1:
      printf("Monday.\n");
      break;
    case 2:
      printf("Tuesday.\n");
      break;
    case 3:
      printf("Wednesday.\n");
      break;
  }
  return 0;
}

The default block

This program sets day to 9. No case matches, so the default block runs.

#include <stdio.h>

int main() {
  int day = 9;
  switch (day) {
    case 1:
      printf("Monday.\n");
      break;
    case 2:
      printf("Tuesday.\n");
      break;
    case 3:
      printf("Wednesday.\n");
      break;
    default:
      printf("Not a weekday.\n");
      break;
  }
  return 0;
}

Missing break runs on

This program sets level to 1. The first case has no break, so the second case runs as well.

#include <stdio.h>

int main() {
  int level = 1;
  switch (level) {
    case 1:
      printf("One.\n");
      /* fall through */
    case 2:
      printf("Two.\n");
      break;
  }
  return 0;
}

Example

#include <stdio.h>

int main() {
  int grade = 3;
  switch (grade) {
    case 1:
      printf("First place.\n");
      break;
    case 2:
      printf("Second place.\n");
      break;
    case 3:
      printf("Third place.\n");
      break;
    default:
      printf("No medal.\n");
      break;
  }
  return 0;
}

Key points

  • A switch statement starts with the word switch and a value in round brackets.
  • Each case names one value that the switch value may match.
  • The code after a matching case runs.
  • break after a case ends the switch statement.
  • Without break, the program runs into the next case too.
  • default runs when no case matches the value.
  • A switch value is often an int variable.

grade is 3, so the case for 3 matches and its line prints. The break after it ends the switch.

Note

Put break at the end of every case, unless you want the next case to run too.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens when break runs at the end of a case?