Skip to the workspace
Pebellslearn by building
Control Flow  ›  Lesson

if, else and switch

if else / switch 14 minif 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.

c / if, else and switch

Explore each scene at your own pace.

01 · The rule

The rule

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. Not double, and not a string.
  • Each case label must be an integer constant expression, such as 3 or 'C', with no duplicates. A const int variable does not qualify in C.
  • After jumping to a case, execution runs straight on through the following cases until a break or the end of the switch. This is called fall-through.
  • default catches every value with no matching case. Include one.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.