The typical case with switch-case conditional statements is that when a case gets executed the switch-case condition doesn't stop its execution at that point rather it executes all the subsequent cases following the case which is executed first. Lets take a look at an example to understand this concept.
Consider the following fragment of program
switch(ch) { case 1 : printf("\n%d + %d = %d", n1, n2, n1 + n2) ; case 2 : printf("\n%d - %d = %d", n1, n2, n1 - n2) ; case 3 : printf("\n%d * %d = %d", n1, n2, n1 * n2); case 4 : printf("\n%d / %d = %.2f", n1, n2, (float)n1 / n2); default : printf("\nInvalid choice"); }
Now suppose we already have two numbers n1 = 10 and n1 = 5 and user wants case 1 to execute so he enters ch = 1.
Output in this case will be -
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2.00
Invalid choice
Now what happens is that, first, case 1 will get executed printing the sum of n1 and n2. But next the program will continue to execute each case after the case 1 until all cases have been executed or a break statement is encountered. So the output of the above was like that.
How to fix this problem?
This problem can be solved by the presence of the break statement at the conclusion of each case block. If a break statement isn’t present, all subsequent case blocks will execute until a break statement is located. So placing a break statement after each case can make the problem go away. Here is the correct version of above fragment of code.
Output of above fragment with n1 = 10 and n2 = 5 and user wants case 1 to execute so he enters ch = 1 will beOutput in this case will be -
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2.00
Invalid choice
Now what happens is that, first, case 1 will get executed printing the sum of n1 and n2. But next the program will continue to execute each case after the case 1 until all cases have been executed or a break statement is encountered. So the output of the above was like that.
How to fix this problem?
This problem can be solved by the presence of the break statement at the conclusion of each case block. If a break statement isn’t present, all subsequent case blocks will execute until a break statement is located. So placing a break statement after each case can make the problem go away. Here is the correct version of above fragment of code.
switch(ch) { case 1 : printf("\n%d + %d = %d", n1, n2, n1 + n2) ; break ; case 2 : printf("\n%d - %d = %d", n1, n2, n1 - n2) ; break ; case 3 : printf("\n%d * %d = %d", n1, n2, n1 * n2); break ; case 4 : printf("\n%d / %d = %.2f", n1, n2, (float)n1 / n2); break ; default : printf("\nInvalid choice"); break ; // Not necessary but you can place it anyway. }
10 + 5 = 15
Tip: As the default case is the last case, you can remove the break statement as the switch condition will automatically gets terminate after default statement.