Code Point Blog

Iam presenting here ,all type of knowledge if you want to interest knowing about any topic then click below thumbnail view button and knowing.

All Chapter Back to Home Page

Switch Statement

The switch statement allows you to choose among multiple cases based on the value of a variable or an expression. It works by evaluating the expression once and then comparing its value to the constant values specified in each case. If a match is found, the code block associated with that case is executed.

The syntax of the switch statement in C is as follows:

    
    #include <stdio.h>
    switch (expression) { 
        case value1: 
         ( Code to be executed if 'expression' equals 'value1' ) 
        break; 
         case value2: 
        ( Code to be executed if 'expression' equals 'value2' ) 
         break; 
         ( Additional cases as needed ) 
        default: 
         ( Code to be executed if 'expression' does not match any case )
         } 
                            
            
            

Key points to remember about the switch statement:

1. The expression must evaluate to an integral or enumerated data type (char, int, enum, etc.).

2. Each case label (value1, value2, etc.) must be a constant value that can be compared to the value of the expression.

3. The break statement is used to exit the switch block once a case is matched. Without break, the execution would continue into the next case (fall-through behavior), which can be intentionally used for certain scenarios.

4. The default case is optional and is executed when the value of the expression does not match any of the case labels.

Here's an example of using the switch statement in C:

     
    #include <stdio.h>
    int main() { 
        char grade = 'B'; 

        switch (grade) { 
        case 'A': 
        printf("Excellent!\n"); 
        break; 
        case 'B': 
        printf("Good!\n"); 
        break; 
        case 'C': 
        printf("Average.\n"); 
        break; 
        default: 
        printf("Invalid grade.\n"); 
        } 

        return 0; 
        } 
                                
    
    

The switch statement is widely used in C programming to make decisions based on different cases, making the code more concise and readable compared to using multiple if-else statements.