CodeBlanks Logo Icon CodeBlanks

The switch statement

Learn multi-way selection with switch, case, break and default.

The switch statement

When a single variable is matched against several constant values, the switch statement is cleaner than an if/else if chain. The form is switch (x) { case 1: ...; break; case 2: ...; break; default: ...; }.

The code after each case label runs for that case; break exits the switch. Without break execution falls through to the next case. default runs when no case matches.

Fall-through without break

If you omit break inside a switch, execution continues to the next case. This is called fall-through. Sometimes the behavior is intentional: when several cases run the same code you list them on top of each other and put break only on the last one.

Most of the time, however, forgetting break is a bug; an unexpected case runs. Compilers usually warn about cases without break. Marking intentional fall-through with a comment is a good habit.

Practice Print the day name

The day variable is set to 2. Use switch (day) so that in case 2 the program prints "Tuesday". Add a break too.

Starter code

main.cpp
#include <iostream>

int main() {
    int day = 2;
    // Print the day name with switch
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    int day = 2;
    switch (day) {
        case 2:
            std::cout << "Tuesday" << std::endl;
            break;
    }
    return 0;
}

Expected output

Tuesday

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each switch part to its role

Term Meaning
switch Starts the selection
case Case label
break Ends the branch
default When none match

2 Which keyword runs when no case matches in a switch?

main.cpp
switch (x) {
  case 1: ...; break;
  ...
}
  • case
  • break
  • default Correct answer
  • switch

Explanation: default runs when no case matches.

3 Write the break keyword

Question
case 1: std::cout << "Monday";
    ____;
Answer
case 1: std::cout << "Monday";
    break;

Explanation: break exits the switch. stop, exit and end are not switch keywords.

All lessons in Beginner