Why is default statement used in switch case in C?
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.
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of C Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.