C++17: Fallthrough in switch statements

A C++ switch statement allows execution to fall through from one case to the next case when a break statement is missing. For example:

#include <iostream>

using namespace std;

enum class Mode
{
    Default,
    Custom
};

class Parameters {};

Parameters AskUserForCustomParameters()
{
    cout << "Asking user for custom parameters..." << endl;
    return Parameters();
}

void Process(const Parameters& parameters)
{
    cout << "Processing parameters..." << endl;
}

void DoSomething(Mode mode)
{
    Parameters parameters;  // Create a default set of parameters
    switch (mode)
    {
    case Mode::Custom:
        AskUserForCustomParameters();
    case Mode::Default:
        Process(parameters);
        break;
    }
}

int main()
{
    DoSomething(Mode::Custom);

    cout << endl;

    DoSomething(Mode::Default);
}

Of course, in this case we could just have used an if statement, but that wouldn’t demonstrate fallthrough in switch statements.

If you look at the code, the case for Mode::Custom does not contain a break statement. Some compilers will issue a warning for this kind of fallthrough because it might be unintended and a source of bugs. C++17 introduced a [[fallthrough]] attribute that you can use to specify in code that a fallthrough is intentional and should not generate a warning. Here is the modified fragment:

void DoSomething(Mode mode)
{
    Parameters parameters;  // Create a default set of parameters
    switch (mode)
    {
    case Mode::Custom:
        AskUserForCustomParameters();
        [[fallthrough]];
    case Mode::Default:
        Process(parameters);
        break;
    }
}

You don’t need to use the [[fallthrough]] attribute for empty switch cases. No compiler will issue a warning for fallthrough with empty case statements. For example:

enum class Mode
{
    Default,
    Custom,
    Standard
};

void DoSomething(Mode mode)
{
    Parameters parameters;  // Create a default set of parameters
    switch (mode)
    {
    case Mode::Custom:
        AskUserForCustomParameters();
        [[fallthrough]];
    case Mode::Standard:
    case Mode::Default:
        Process(parameters);
        break;
    }
}

My book, Professional C++, 4th Edition, explains all new C++17 features, and much more.

Share

Leave a Comment

Name: (Required)

E-mail: (Required)

Website:

Comment: