C: Switch Case
A switch
is a decision making statement which tests the value of a given single variable against a list of case
values. A case
statement is followed by a value (which is an int
or a char
) and a colon.
Syntax
The syntax of switch statement is
switch(expression)
{
case value1:
// some code
break;
case value2:
// some code
break;
case value3:
// some code
break;
...
default:
// some code
}
When the switch expression matches with a case constant, the control of the program passes to the code block within that case until the break
statement, when it terminates and exits from the switch
block. The default
block is executed when the switch expression does not match with any of the case values; it, however, is an optional case.
Integer Case Values
When an integer is divided by 2, the remainder is always 0 or 1 depending on the integer being even or odd respectively. In the below example, we create a switch statement with integer case values/labels based on the value of r
, which is either 0 or 1 depending on whether n
is even or odd
#include <stdio.h>
main() {
int n, r;
printf("Integer: ");
scanf("%d", &n);
r = n%2; // r is 0 for even; 1 for odd
switch(r) {
case 0:
printf("%d is an even number", n);
break;
case 1:
printf("%d is an odd number", n);
break;
default:
printf("%d is some other number", n);
}
}
Multiple Case Labels
Two or more cases may share a single break statement. We illustrate it in the below example using labels of type char
#include <stdio.h>
main() {
char letter;
printf("Letter: ");
scanf("%c", &letter);
switch(letter) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("%c is a vowel", letter);
break;
default:
printf("%c is a consonant", letter);
}
}
Notes
- Case value/label must be unique.
-
Logical opertors cannot be used as
case
values/labels.