switch
When you compare one variable against many exact values, switch is neater than a long else if chain:
#include <stdio.h>
int main() {
int day;
scanf("%d", &day);
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Another day\n");
}
return 0;
}Input (what the user types)
2
Output
Tuesday
switch (day)looks at the value ofday.- It jumps to the matching
case. breakleaves theswitch.defaultruns when no case matches (likeelse).
Common mistake: Forgetting
break. Without it, C keeps going and runs the next cases too! This is called falling through.
Sometimes falling through is useful, to give several cases the same code:
#include <stdio.h>
int main() {
char c = 'e';
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("%c is a vowel\n", c);
break;
default:
printf("%c is a consonant\n", c);
}
return 0;
}Output
e is a vowel
Tip:
switchworks with whole numbers and characters, not with decimals or text.
The ? : operator
To pick between two values in one line, use condition ? valueIfTrue : valueIfFalse:
#include <stdio.h>
int main() {
int a = 8;
int b = 13;
int bigger = (a > b) ? a : b;
printf("Bigger: %d\n", bigger);
return 0;
}Output
Bigger: 13
Remember: Use
if/elsefor most decisions,switchfor many exact values, and? :for a quick choice between two values.