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 task

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

Challenge 2

Read a weapon slot number and print what's in it: 1 is rifle, 2 is pistol, 3 is knife, 4 is grenade, and anything else is empty.

Challenge 3

Read a single letter and print the map it stands for. Both lowercase and uppercase must work: d or D is Dust II, m or M is Mirage, i or I is Inferno. Anything else prints unknown map. Use a switch and let two cases share the same code.

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