← Exercises|

Repair: a switch that falls through

Repair8 of 14 · about 6 min

Repair: a switch that falls through

A switch jumps to the matching case and then keeps running — through the next case, and the one after that — until it meets a break or the end of the switch. That is called fall-through, and it is deliberate: it is how several labels share one piece of code.

It is also the most common way a switch goes wrong, because a missing break looks like nothing at all.

When you mean to fall through, say so in a comment. Reviewers and compilers both look for it.

Example

switch (c) {
    case 'a':
    case 'e':            /* deliberate: both share the body below */
        vowels++;
        break;
    default:
        others++;
}

Your task

This grader is meant to print one line per score. It prints too much. Fix it without changing the structure — the labels and the messages are all correct.

Stuck?

Explain it

Why is the last default allowed to have no break?

Not graded — this is for you.

Where this goes

Project 4 asks for a command dispatcher built on a switch. This is the failure it will hand you if you forget one break.