Home C Programming Tutorial Switch Statement in C

Switch Statement in C

by Anup Maurya
3 minutes read

C switch statement is used when you have multiple possibilities for the if statement. Switch case will allow you to choose from multiple options.

When we compare it to a general electric switchboard, you will have many switches in the switchboard but you will only select the required switch, similarly, the switch case allows you to set the necessary statements for the user.


switch (n) {     
           case 1: // code to be executed if n = 1;      
           case 2: // code to be executed if n = 2;       
           default: // code to be executed if n doesn't match any cases

Important Points about Switch Case Statements:  

1. The expression provided in the switch should result in a constant value otherwise it would not be valid. 
Valid expressions for switch:

// Constant expressions allowed

// Variable expression are allowed provided
// they are assigned with fixed values

2. Duplicate case values are not allowed.

3. The default statement is optional. Even if the switch case statement do not have a default statement, 
it would run without any problem.

4. The break statement is used inside the switch to terminate a statement sequence. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

5. The break statement is optional. If omitted, execution will continue on into the next case. The flow of control will fall through to subsequent cases until a break is reached.

6. Nesting of switch statements are allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes program more complex and less readable. 


#include <stdio.h>
int main () {

   /* local variable definition */
   char grade = 'A';

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


Your grade is A

related posts

Leave a Comment