C/C++ Arena

Step 4 of 6

switch

When one value is compared against a list of constant possibilities, switch is often clearer than a long else if chain:

#include <stdio.h>

int main(void) {
    int day;
    scanf("%d", &day);
    switch (day) {
        case 6:
        case 7:
            printf("weekend\n");
            break;
        case 5:
            printf("almost weekend\n");
            break;
        default:
            printf("weekday\n");
    }
    return 0;
}
7
weekend

How it works

switch evaluates the value in parentheses once, then jumps to the case label with the matching constant. From there, it runs statements downward until it hits a break (which leaves the switch) or the end. If no case matches, it jumps to default, or does nothing if there's no default.

Fall-through

Because execution continues until a break, forgetting one makes the program fall through into the next case and run its code too. That's a very common bug. It's also occasionally useful on purpose, as with case 6: and case 7: above sharing the same code.

Limits

case labels must be constant integer values, which includes characters like 'q'. You can't use ranges, strings or variables as labels; use if/else if for those.

Your turn: read a char and print the direction for w, a, s, d (forward, left, back, right), or unknown for anything else.

Previous: And, or, not Next: The ternary operator