C Switch Statement

The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single variable.

The syntax of switch statement in c language is given below:

Syntax

                    
switch(expression){    
case value1:    
//code to be executed;    
break;  //optional  
case value2:    
//code to be executed;    
break;  //optional  
......    
            
default:     
code to be executed if all cases are not matched;    
}         

               
                

Rules for switch statement in C language

  1. The switch expression must be of an integer or character type.

  2. The case value must be an integer or character constant.

  3. The case value can be used only inside the switch statement.

  4. The break statement in switch case is not must. It is optional. If there is no break statement found in the case, all the cases will be executed present after the matched case. It is known as fall through the state of C switch statement.

Let's try to understand it by the examples. We are assuming that there are following variables.

int x,y,z;
char a,b;
float f;

Valid and Invalid Switch Statements and Cases

The table below evaluates the validity of various switch statements and case labels in C programming, along with explanations.

Statement/Case Valid/Invalid Explanation
switch(x) Valid The expression x is an integer type, suitable for switch.
switch(f) Invalid The expression f is a float, which is not allowed in a switch.
case 3; Valid The case label is an integer constant, which is valid.
case 2.5; Invalid The case label is a float constant, which is not allowed.
switch(x > y) Invalid The expression x > y evaluates to a boolean, which is not valid in a switch.
switch(x + 2.5) Invalid The expression x + 2.5 includes a float, which is invalid for switch.
case 'a'; Valid The case label is a character constant, which is allowed.
case x; Invalid The case label is a variable, which is not a constant value.
switch(a + b - 2) Valid The expression is an integer calculation, valid for switch.
case 1 + 2; Valid The case label is a constant integer expression, which is allowed.
case x + 2; Invalid The case label includes a variable, which is not a constant value.
switch(func(x, y)) Invalid The switch expression calls a function, which is not a constant value.
case 'x' > 'y'; Invalid The case label is a boolean result, which is not allowed in switch.
case 1, 2, 3; Invalid Comma-separated values are not valid case labels.

Flowchart of switch statement in C

Functioning of switch case statement

First, the integer expression specified in the switch statement is evaluated. This value is then matched one by one with the constant values given in the different cases. If a match is found, then all the statements specified in that case are executed along with the all the cases present after that case including the default statement. No two cases can have similar values. If the matched case contains a break statement, then all the cases present after that will be skipped, and the control comes out of the switch. Otherwise, all the cases following the matched case will be executed.

How does C switch statement work?

Let's go through the step-by-step process of how the switch statement works in C:
Consider the following switch statement:

Example

                
#include<stdio.h>   
int main() 
{  
    int num = 2;  
    switch (num) {  
    case 1:  
    printf("Value is 1\n");  
    break;  
    case 2:  
    printf("Value is 2\n");  
    break;  
    case 3:  
    printf("Value is 3\n");  
    break;  
    default:  
    printf("Value is not 1, 2, or 3\n");  
    break;  
    }  
      
    return 0;  
}  
 
                    
                
            

Output

Value is 2

Step-by-step Process:

  1. The switch variable num is evaluated. In this case, num is initialized with the value 2.
  2. The evaluated num (2) value is compared with the constants specified in each case label inside the switch block.
  3. The switch statement matches the evaluated value (2) with the constant specified in the second case (case 2). Since there is a match, the program jumps to the code block associated with the matching case (case 2).
  4. The code block associated with case 2 is executed, which prints "Value is 2" to the console.
  5. The "break" keyword is present in the code block of case 2. As a result, the program breaks out of the switch statement immediately after executing the code block.
  6. The program control continues after the switch statement, and any statements following the switch statement are executed. In this case, there are no statements after the switch, so the program terminates.
  7. The switch statement evaluated the value of the variable num, found a match with case 2, executed the corresponding code block, and then exited the switch block due to the presence of the "break" statement.

Example of a switch statement in C

Let us see a simple example of a C language switch statement.

Example

            
#include<stdio.h>   
int main()
{    
    int number=0;     
    printf("enter a number:");    
    scanf("%d",&number);    
    switch(number){    
    case 10:    
    printf("number is equals to 10\n");    
    break;    
    case 50:    
    printf("number is equal to 50\n");    
    break;    
    case 100:    
    printf("number is equal to 100\n");    
    break;    
    default:    
    printf("number is not equal to 10, 50 or 100\n");    
    }    
    return 0;  
}      
  

                
            
        

Output

enter a number:4 number is not equal to 10, 50 or 100 enter a number:50 number is equal to 50

Switch case example 2

            
#include<stdio.h>   
int main()  
{  
    int x = 10, y = 5;   
    switch(x>y && x+y>0)  
    {  
        case 1:   
        printf("hi\n");  
        break;   
        case 0:   
        printf("bye\n");  
        break;  
        default:   
        printf(" Hello bye\n ");  
    }   
          
}  
 
            
        

Output

hi

Break and Default keyword in Switch statement

Let us explain and define the "break" and "default" keywords in the context of the switch statement, along with example code and output.

1. Break Keyword:

he "break" keyword is used within the code block of each case to terminate the switch statement prematurely. When the program encounters a "break" statement inside a case block, it immediately exits the switch statement, preventing the execution of subsequent case blocks. The "break" statement is crucial for avoiding switch statements' "fall-through" behavior

Example:

Let's take a program to understand the use of the break keyword in C.

Example:

            
#include<stdio.h>   
int main() 
{  
    int num = 3;  
      
    switch (num) {  
    case 1:  
    printf("Value is 1\n");  
    break; // Exit the switch statement after executing this case block  
    case 2:  
    printf("Value is 2\n");  
    break; // Exit the switch statement after executing this case block  
    case 3:  
    printf("Value is 3\n");  
    break; // Exit the switch statement after executing this case block  
    default:  
    printf("Value is not 1, 2, or 3\n");  
    break; // Exit the switch statement after executing the default case block  
    }  
      
    return 0;  
}    

 
            
        

Output

Value is 3

2. Default Keyword:

When none of the case constants match the evaluated expression, it operates as a catch-all case. If no matching case exists and a "default" case exists, the code block associated with the "default" case is run. It is often used to handle circumstances where none of the stated situations apply to the provided input.

Example:

            
#include<stdio.h>   
int main() 
{  
    int num = 5;  
      
    switch (num) {  
    case 1:  
    printf("Value is 1\n");  
    break;  
    case 2:  
    printf("Value is 2\n");  
    break;  
    case 3:  
    printf("Value is 3\n");  
    break;  
    default:  
    printf("Value is not 1, 2, or 3\n");  
    break; // Exit the switch statement after executing the default case block  
    }  
      
    return 0;  
}       

 
            
        

Output

Value is not 1, 2, or 3

Nested switch case statement

We can use as many switch statement as we want inside a switch statement. Such type of statements is called nested switch case statements. Consider the following example.

            
#include<stdio.h>   
int main () 
{  
  
    int i = 10;  
    int j = 20;  
    
    switch(i) {  
      
       case 10:   
          printf("the value of i evaluated in outer switch: %d\n",i);  
       case 20:  
          switch(j) {  
             case 20:  
                printf("The value of j evaluated in nested switch: %d\n",j);  
          }  
    }  
      
    printf("Exact value of i is : %d\n", i );  
    printf("Exact value of j is : %d\n", j );  
    
    return 0;  
 }    
  

 
            
        

Output

the value of i evaluated in outer switch: 10 The value of j evaluated in nested switch: 20 Exact value of i is : 10 Exact value of j is : 20

Advantages of the switch statement:

There are several advantages of the switch statement in C. Some main advantages of the switch statement are as follows:

Disadvantages of the switch statement:

There are several disadvantages of the switch statement in C. Some main disadvantages of the switch statement are as follows: