C Switch Statement
The switch statement chooses one block from many options, based on the value of a variable. It is cleaner than a long if else ladder when you compare one variable with fixed values.
Syntax
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code if nothing matches
}
Example: day name
#include <stdio.h>
int main(void) {
int day = 3;
switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
default: printf("Other day\n");
}
return 0;
}
Output:
Output of the above program is
Wednesday
Without break (fall through)
If you forget break, the program continues to the next case also.
#include <stdio.h>
int main(void) {
int n = 1;
switch (n) {
case 1: printf("One\n");
case 2: printf("Two\n");
case 3: printf("Three\n"); break;
default: printf("Other\n");
}
return 0;
}
Output:
Output of the above program is
One
Two
Three
Sometimes fall through is useful. Many cases can share one block:
#include <stdio.h>
int main(void) {
char ch = 'e';
switch (ch) {
case 'a': case 'e': case 'i': case 'o': case 'u':
printf("Vowel\n");
break;
default:
printf("Consonant\n");
}
return 0;
}
Output:
Output of the above program is
Vowel
Rules
- The expression must be an integer or a character. You cannot use float or string.
- Case values must be constants and cannot repeat.
defaultis optional and can be written at any place, but is usually last.
Note:
Use break after every case, unless you want the fall through on purpose.
Next: C While Loop.
Congratulations! Chapter Finished. Learn more about the similar topics: