what is the purpose of using break statement in switch case
Answers
When using switch case there are obviously two or more cases in it. So, whenever a case is being executed it is important that it gets terminated after executing that particular case.
Consider the example given below. If case B had a break statement then the output would've been "Well Done ! Your grade is B" but since we didn't use a break statement in the below example the out put would be a combination of case B & case C. The reason it terminates at C is because there's a break statement.
Program:
char grade = B;
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
printf("Well done !\n" );
case 'C' :
printf("You passed\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
Output:
Well done
You passed
Your grade is B