C/C++ Arena

Step 4 of 6

switch

When you compare one value against many constants, switch is tidier than a long else if chain:

switch (key) {
    case 'w':
        printf("forward\n");
        break;
    case 's':
        printf("back\n");
        break;
    default:
        printf("?\n");
}

Each case needs a break;, otherwise execution falls through into the next case. default catches everything else.

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