Why is default statement used in switch case in C?

C Programming Language >   Decision Making of C Language >   switch case  

Short Question

961


Answer:

Switch case statements are used to execute only specific case statements based on the switch expression. If switch expression does not match with any case, default statements are executed by the program.

The default statement in a switch case in C is used as a catch-all for any cases that are not explicitly handled by the other case statements. It is typically used to handle unexpected input or to provide a default behavior for the switch statement. The code block associated with the default statement is executed when no other case statement's value matches the expression being evaluated.

Example


int x = 3;

switch (x) {
    case 1:
        printf("x is 1");
        break;
    case 2:
        printf("x is 2");
        break;
    default:
        printf("x is not 1 or 2");
        break;
}

In this example, if x=3 which is not handled by any of the case statement, the default statement will be executed.


This Particular section is dedicated to Question & Answer only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.