if, else and switch
if and else choose based on any condition, while switch jumps to the case whose integer constant matches a value and keeps running into later cases until it meets a break.
Follow branch selection, case labels and fall-through on a concrete input.
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.