Home C Programming Tutorial Switch Statement in C

Switch Statement in C

by anupmaurya

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.

Syntax:

switch (n) {     
           case 1: // code to be executed if n = 1;      
                    break;    
           case 2: // code to be executed if n = 2;       
                    break;     
           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
          switch(1+2+23)
          switch(1*2+3%4)

// Variable expression are allowed provided
// they are assigned with fixed values
        switch(a*b+c*d)
        switch(a+b+c)

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. 

Example

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

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

   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;
}

Output

Excellent
Your grade is A

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.