C switch
Statement
A switch statement allows testing a variable against multiple values. Each value is called a case, and the variable being tested is checked against each switch case.
Syntax
The syntax for a switch statement in C:
switch(expression){
case constant-expression :
statement(s);
break; /* Optional */
case constant-expression :
statement(s);
break; /* Optional */
/* You can have any number of case statements */
default : /* Optional */
statement(s);
}
switch statements must follow these rules:
- The expression in a switch statement is a constant expression and must be an integer or enumerated type.
- A switch can have any number of case statements. Each case is followed by the value to be compared and a colon.
- The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or literal.
- When the variable being tested equals the constant in a case, the statements following that case will execute until a break statement is encountered.
- When a break statement is encountered, the switch terminates, and the control flow jumps to the next line following the switch statement.
- Not every case needs to contain a break. If a case statement does not have a break, the control flow will continue into subsequent cases until a break is encountered.
- A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used to perform a task when none of the cases are true. The break statement is not required in the default case.
Flowchart
Example
#include <stdio.h>
int main ()
{
/* Local variable definition */
char grade = 'B';
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
When the above code is compiled and executed, it produces the following result:
Well done
Your grade is B