Easy Tutorial
❮ C Examples Negative Positive Zero C Examples Dynamic Memory Allocation Largest ❯

C switch Statement

C Decision

A switch statement allows testing a variable against multiple values. Each value is called a case, and the variable being tested is checked against each switch case.

Syntax

The syntax for a switch statement in C:

switch(expression){
    case constant-expression  :
       statement(s);
       break; /* Optional */
    case constant-expression  :
       statement(s);
       break; /* Optional */

    /* You can have any number of case statements */
    default : /* Optional */
       statement(s);
}

switch statements must follow these rules:

Flowchart

Example

#include <stdio.h>

int main ()
{
   /* Local variable definition */
   char grade = 'B';

   switch(grade)
   {
   case 'A' :
      printf("Excellent!\n" );
      break;
   case 'B' :
   case 'C' :
      printf("Well done\n" );
      break;
   case 'D' :
      printf("You passed\n" );
      break;
   case 'F' :
      printf("Better try again\n" );
      break;
   default :
      printf("Invalid grade\n" );
   }
   printf("Your grade is %c\n", grade );

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Well done
Your grade is B

C Decision

❮ C Examples Negative Positive Zero C Examples Dynamic Memory Allocation Largest ❯