What will happen if break statement is not used in switch case in C?

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

Short Question

5204


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.
If a break statement is not used in a switch case in C, the code will continue to execute the following cases until a break or the end of the switch statement is reached. This can lead to unexpected results, as multiple cases may be executed even if only one case is intended to be executed. It is important to use the break statement in each case to ensure that only the intended case is executed and to avoid fall-through.

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.


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.