What will happen if break statement is not used in switch case in C?
Answer:
- Switch case statements are used to execute only specific case statements based on the switch expression.
- If we do not use break statement at the end of each case, program will execute all consecutive case statements until it finds next break statement or till the end of switch case block.
Example
If the break statement is not used in a switch case in C, the code will continue to execute the next case statement(s) after a match is found.
For example:
switch (x) { case 1: printf("Case 1"); case 2: printf("Case 2"); case 3: printf("Case 3"); }
If the value of x is 1, the output will be "Case 1Case 2Case 3". This is because after the first match, the code continues to execute the next case statements, instead of breaking out of the switch statement with the use of the break statement.
To avoid this problem, the break statement should be used at the end of each case block.
switch (x) { case 1: printf("Case 1"); break; case 2: printf("Case 2"); break; case 3: printf("Case 3"); break; }
This way, when the program reaches the matching case, it will break out of the switch statement and will not execute any other cases.
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.