switch and the conditional operator
switch jumps to the case that matches and runs on until break; grouped cases; why switch cannot test ranges; choosing a structure; and ?:, which evaluates only the value it chooses.
switch: choose by one exact value
The chamber controller has three modes, and each mode has its own temperature limit: N (normal) 80 °C, T 70 °C, S 60 °C. One value (mode) is compared with a few exact constants. That is the job of switch.
switch (mode) {
case 'N':
limit = 80;
break;
case 'T':
limit = 70;
break;
case 'S':
limit = 60;
break;
default:
limit = -1;
}What the computer does with mode = 'T':
- It evaluates
modeonce. - It jumps straight to the label
case 'T':. It does not test'N'first the way an else-if chain would. - It runs
limit = 70;. breakleaves the switch. The program continues after the closing}.
If no case matches (mode = 'X'), C jumps to default. A switch without a default simply does nothing for an unexpected value, and limit keeps whatever it had: often an uninitialised variable. Every switch should have a default.
A switch is a good fit when:
- there is one value to test,
- that value is an
intor achar(acharis a small integer in C, so'N'works as a label), - it is compared with constant labels,
- there are several named choices.
Fall-through: a case is an entry point
A case label is only a place to enter. C does not stop at the next label. It keeps running down until it meets a break or the end of the switch. This is called fall-through.
switch (code) {
case 1: printf("A");
case 2: printf("B");
case 3: printf("C"); break;
default: printf("D");
}| code | enters at | runs | output |
|---|---|---|---|
| 1 | case 1 | A, B, C, then break | ABC |
| 2 | case 2 | B, C, then break | BC |
| 3 | case 3 | C, then break | C |
| 4 | default | D, end of switch | D |
Grouped cases: fall-through on purpose
Sometimes several values should do the same thing. Then fall-through is useful:
switch (command) {
case 'R':
case 'r':
printf("RESET");
break;
case 'S':
case 's':
printf("STATUS");
break;
default:
printf("INVALID");
}With command = 'R', C enters at case 'R':. That label has no statements, so C runs on into the code under case 'r':, prints RESET, and leaves at break. Both letters share one printf. Writing printf("RESET") twice would work too, but then there are two places to change when the message changes.
When the reason for a fall-through is not obvious, write a short comment such as /* falls through on purpose */.
switch cannot test a range
This looks tempting, and it does not compile:
/* Invalid idea */
switch (temperature) {
case temperature >= 80:
state = 3;
break;
}error C2051: case expression not constantA case label must be an integer constant: a number such as 80 or a character such as 'N', known when the program is compiled. A comparison that depends on a variable is not allowed.
- Exact values →
switch. - Ranges →
if/else if. - Both → mix them: a switch on the mode to pick the limit, then an if chain on the temperature. Lesson 3 builds exactly that.
Which structure fits?
| Situation | Prefer | Why |
|---|---|---|
| mode is 'N', 'T' or 'S' | switch | one value, exact constants |
| temperature below 60, 60 to 79, 80 or more | else if | ranges need < and >= |
| temperature matters only if the battery is fine | nested if | the second question depends on the first |
| pick the larger of two numbers | ?: | one small value from two |
Two structures can often both produce the right output. Choose the one that shows the shape of the specification: someone reading the code should see at once "these are exact choices" or "these are ranges".
The conditional operator ?:
The conditional operator (אופרטור התנאי) chooses one of two values:
result = condition ? value_if_true : value_if_false;Read it as: "if the condition is true, this value, otherwise that value".
int larger = (a > b) ? a : b;
char lamp = alarm ? 'R' : 'G';With a = 5, b = 8: (a > b) is false, so larger gets b, which is 8. With alarm = 1: the lamp is 'R'.
C evaluates the condition first and then only the chosen value. The other value is never evaluated, just like the right side of a short-circuited &&. So this is safe even when divisor is 0:
int value = (divisor != 0) ? total / divisor : -1;Clear beats clever
?: is good for one short choice. Nesting it is legal, but hard to read:
state = battery < 15 ? 3 :
temperature >= 80 ? 3 :
temperature >= 60 ? 2 : 1;The same decision as an if chain is easy to check line by line:
if (battery < 15 || temperature >= 80)
state = 3;
else if (temperature >= 60)
state = 2;
else
state = 1;Use ?: when both results fit in one short thought.
Precedence: add the parentheses
What prints?
int a = 5;
int b = 8;
int result;
result = a > b ? a : b + 10;
printf("%d", result);18?: has very low precedence, so C reads the line as result = (a > b) ? a : (b + 10);. The condition 5 > 8 is false, so the second value is chosen, and the second value is the whole b + 10, which is 18.
Do not rely on the reader knowing the precedence table. Write the parentheses yourself: result = (a > b) ? a : (b + 10);.
Exit check
Answer without compiling:
int x = 2;
int y = 5;
int z = (x > y) ? x : y;
switch (z) {
case 5: printf("A");
case 6: printf("B"); break;
default: printf("C");
}ABz gets the larger value, 5. C enters at case 5, prints A, finds no break, falls into case 6, prints B and stops at its break. To print only A, add break; after printf("A");.
Key words
| English | Hebrew | Meaning |
|---|---|---|
| switch | משפט switch | chooses a path by one exact value |
| case label | תווית case | an entry point inside the switch |
| break | יציאה מה־switch | leaves the switch at once |
| default | ברירת מחדל | runs when no case matches |
| fall-through | המשך ל־case הבא | running on into the next case |
| integer constant | קבוע שלם | what a case label must be |
conditional operator ?: | אופרטור התנאי | chooses one of two values |
| precedence | קדימות אופרטורים | which operator groups first |
Practice
More questions, with answers, on the practice page: challenges 3, 4, 5, 10 and 11 and problems 11-24 fit this lesson.