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;
 
  switch(num){
    
    case 4:
      printf("The number is four.\n");
break;
    case 6:
      printf("The number is six.\n");
break;
    case 8:
      printf("The number is eight.\n");
     break;
  }
 
  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;
 
  switch(--a){
    
    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");
  switch((a=getchar())){
    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.");
    break;
    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.");
    break;
    default:
    printf("The character is a consonant.");
    break;
  }
        
  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:

http://www.amazon.com/Big-Als-C-Standard-ebook/dp/B00A4JGE0M/

As well as my book on Linux:

http://www.amazon.com/Big-Als-Linux-Fedora-CLI-ebook/dp/B00GI25V30/

Advertisements