Search code examples
c++cswitch-statementgoto

How to achieve some exclusive statements and some common statements for multiple cases in a switch?


I have a switch statement where each case has unique code, and some code that is shared between all cases except the default label. Is there a good way to have a shared command between the different case labels?

Edit: code example

switch (c)
{
    case '+':
        command.type = ADD;
        commands.push_back(command);
        break;
    case '-':
        command.type = SUB;
        commands.push_back(command);
        break;
    case '>':
        command.type = INC;
        commands.push_back(command);
        break;
    case '<':
        command.type = DEC;
        commands.push_back(command);
        break;
    case '.':
        command.type = PUT;
        commands.push_back(command);
        break;
    case ',':
        command.type = GET;
        commands.push_back(command);
        break;
    default: break;

Solution

    • Set a flag to true
    • in the default case of the switch, set the flag to false
    • run the common code if the flag is true.

    Something like the following:

    bool MyPushBackFlag = true;
    switch (c)
    {
        case '+':
            command.type = ADD;
            break;
        case '-':
            command.type = SUB;
            break;
        case '>':
            command.type = INC;
            break;
        case '<':
            command.type = DEC;
            break;
        case '.':
            command.type = PUT;
            break;
        case ',':
            command.type = GET;
            break;
        default: MyPushBackFlag = false; break;
    }
    
    if (MyPushBackFlag)
         commands.push_back(command);