The Switch Statement

The switch statement enables us to choose one course of action from a set of possible actions based on the evaluation of an expression.

#include <stdio.h>

int main(void){
  int num = 8;
    case 4:
      printf("The number is four.\n");
    case 6:
      printf("The number is six.\n");
    case 8:
      printf("The number is eight.\n");
  return 0;

As we have seen above, the value of the expression in parentheses following the keyword switch determines which of the statements between the braces will be executed.

The break statement causes switch to skip over the other statements within that block and continue with whatever statement follows the closing brace. If we do not put a break statement in, then a switch statement can end up giving us multiple results. Sometimes, that’s a good thing, and sometimes, that’s a bad thing.

#include <stdio.h>

int main(void){
  int a = 16;
    case 15:
      printf("a == 15\n");
    case 16:
      printf("a == 16\n");
    case 17:
      printf("a == 17\n");
  return 0;

We can associate several case values with one group of statements.

#include <stdio.h>

int main(void){
  char a;
  printf("Enter a letter:\n");
    case 'a':
    case 'A':
    case 'e':
    case 'E':
    case 'i':
    case 'I':
    case 'o':
    case 'O':
    case 'u':
    case 'U':
    printf("The character is a vowel.");
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    printf("The character is a number.");
    printf("The character is a consonant.");
  return 0;

Note that placing a break statement after the default case is not, strictly speaking, necessary.

If you have an Amazon Kindle or Kindle app, take a look at my book on C:

As well as my book on Linux:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s