if, else and switch
The logger now has two decisions to make for every reading: which unit to print it in, Celsius or Fahrenheit, and whether to call it cold, mild or hot. They look alike, but they are different kinds of decision, and C has a different tool for each.
The rule
if tests any condition; switch jumps to the case matching one integer.
if / else runs a block when a condition is nonzero. Chain them with else if to test ranges or any mix of conditions:
if (t < 100) {
printf("cold\n");
} else if (t < 250) {
printf("mild\n");
} else {
printf("hot\n");
}Always use braces. Without them, an else attaches to the nearest unmatched if, whatever the indentation suggests.
switch compares one value against a list of constants and jumps to the matching case:
switch (unit) {
case 'C':
printf("%.1f C\n", t / 10.0);
break;
case 'F':
printf("%.1f F\n", t / 10.0 * 9.0 / 5.0 + 32.0);
break;
default:
printf("unknown unit '%c'\n", unit);
break;
}The rules of switch:
- The controlling value must have an integer type:
int,char, an enum and so on. Notdouble, and not a string. - Each
caselabel must be an integer constant expression, such as3or'C', with no duplicates. Aconst intvariable does not qualify in C. - After jumping to a case, execution runs straight on through the following cases until a
breakor the end of theswitch. This is called fall-through. defaultcatches every value with no matching case. Include one.
The shortcut
Ask: "Am I comparing one integer with a list of exact values?" Yes: switch. Ranges, floating-point values, strings or several variables: an if / else if chain.
The code
switch (unit) { case 'C': print Celsius; case 'F': print Fahrenheit; break; }with nobreakafter the Celsius line.
The compiler can help: GCC and Clang have -Wimplicit-fallthrough (GCC turns it on with -Wextra), which warns when one case runs into the next without a break.
When fall-through is deliberate, for example two cases sharing one action (case 'c': case 'C':), place the labels together. When there is code in between, a comment saying "falls through" tells readers it is intentional.
Drills
Answer fast — trust the rule.
Can a switch test a double reading directly?
What does switch (n) { case 1: printf("A"); case 2: printf("B"); break; default: printf("D"); } print when n is 1?
In if (a) if (b) x = 1; else x = 2;, which if does the else belong to?
Which is the right tool for "below 100 is cold, below 250 is mild, the rest is hot"?
Given const int limit = 5;, is case limit: allowed in C?
Remember
- if tests any condition; switch jumps to the case matching one integer constant.
- Shortcut: one integer against exact values →
switch; ranges or anything else →if/else if. - Trap: a missing
breakfalls through, and an unbracedelsejoins the nearestif.
