Switch Statement in C
Switch Statement in C
switchstatementinC
Cswitchstatement
Advertisements
PreviousPage
NextPage
Aswitchstatementallowsavariabletobetestedforequalityagainstalistofvalues.Eachvalueiscalledacase,andthevariable
beingswitchedonischeckedforeachswitchcase.
Syntax
ThesyntaxforaswitchstatementinCprogramminglanguageisasfollows
switch(expression){
caseconstantexpression:
statement(s);
break;/*optional*/
caseconstantexpression:
statement(s);
break;/*optional*/
/*youcanhaveanynumberofcasestatements*/
default:/*Optional*/
statement(s);
}
Thefollowingrulesapplytoaswitchstatement
Theexpressionusedinaswitchstatementmusthaveanintegralorenumeratedtype,orbeofaclasstypeinwhichthe
classhasasingleconversionfunctiontoanintegralorenumeratedtype.
Youcanhaveanynumberofcasestatementswithinaswitch.Eachcaseisfollowedbythevaluetobecomparedtoanda
colon.
Theconstantexpressionforacasemustbethesamedatatypeasthevariableintheswitch,anditmustbeaconstant
oraliteral.
When the variable being switched on is equal to a case, the statements following that case will execute until a break
statementisreached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the
switchstatement.
Noteverycaseneedstocontainabreak.Ifnobreakappears,theflowofcontrolwillfallthroughtosubsequentcasesuntil
abreakisreached.
Aswitchstatementcanhaveanoptionaldefaultcase,whichmustappearattheendoftheswitch.Thedefaultcasecan
beusedforperformingataskwhennoneofthecasesistrue.Nobreakisneededinthedefaultcase.
FlowDiagram
https://www.tutorialspoint.com/cprogramming/switch_statement_in_c.htm
1/3
11/9/2016
switchstatementinC
Example
#include<stdio.h>
intmain(){
/*localvariabledefinition*/
chargrade='B';
switch(grade){
case'A':
printf("Excellent!\n");
break;
case'B':
case'C':
printf("Welldone\n");
break;
case'D':
printf("Youpassed\n");
break;
case'F':
printf("Bettertryagain\n");
break;
default:
printf("Invalidgrade\n");
}
printf("Yourgradeis%c\n",grade);
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Welldone
YourgradeisB
PreviousPage
NextPage
Advertisements
https://www.tutorialspoint.com/cprogramming/switch_statement_in_c.htm
2/3