The switch Statement

Sometimes a program chooses what to do by the exact value of one variable: button 1 on a drink machine makes coffee, button 2 tea, and so on. You could write that with else if, but C has a tidier statement for it, switch:

int day = 3;

switch (day) {
    case 1:
        printf("Monday\n");
        break;
    case 2:
        printf("Tuesday\n");
        break;
    case 3:
        printf("Wednesday\n");
        break;
    default:
        printf("Another day\n");
        break;
}

This prints:

Wednesday

switch takes the value in the parentheses, here the value of day, and jumps to the case with the same value. After case comes a value and a colon, and below them the statements to run. break ends the switch: the program continues after its closing brace. default catches all the values that have no case of their own, just like else at the end of an else if chain. It's optional, and it's usually written last. In the last branch, break isn't needed, because the switch ends there anyway, but it's a good habit to write it in every branch.

Watch out for break. Without it, the program doesn't stop at the next case: it falls through and runs the statements of the following cases too, until it reaches a break or the end of the switch:

int day = 2;

switch (day) {
    case 1:
        printf("Monday\n");
    case 2:
        printf("Tuesday\n");
    case 3:
        printf("Wednesday\n");
    default:
        printf("Another day\n");
}

This prints:

Tuesday
Wednesday
Another day

The program jumped to case 2 and then ran everything below it. The compiler doesn't report anything, so when a switch prints more than it should, look for a missing break.

Sometimes falling through is just what you want: when several values share the same statements. Then you write their case lines one below another:

int day = 6;

switch (day) {
    case 6:
    case 7:
        printf("Weekend\n");
        break;
    default:
        printf("Workday\n");
        break;
}

This prints:

Weekend

switch works only with whole numbers and characters, such as case 3: or case 'A':. It can't check ranges like temperature > 25, and it doesn't work with decimal numbers: switch (price) with a double makes the compiler report error: statement requires expression of integer type ('double' invalid). For those, use if and else if.

Instructions

The drink machine has a bug: button 2 gives you tea and hot chocolate. Run the program, and then add the missing break so that it prints only Tea and Thank you!.

At the end of the switch, below the last break, add a default branch that prints Unknown button.

Change button to 7 and run the program. No case has the value 7, so the program prints Unknown button and Thank you!.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

11/12