user12241860
user12241860

Reputation:

Switch to execute same function for all cases along with single print statement for one of them

I have a switch case where for all cases the same function is to be executed, however for one of the cases I would also like a print statement to be printed.

I understand that to execute the same function for all cases you do something like this:

switch(caseType)
{
    case A:
    case B:
    case C:
    case D:
        printf("Your case type = %s\n",caseType);
    break;
    default:
        printf("default\n");
    break;
}

In this case it would print the case type for whatever case is passed through caseType.

But what about if I want to for example have a print for case A (if the case == A, as well as the Your case type print?

I tried this, but it did not seem to work the way I wanted (assuming E is the argument passed):

switch(caseType)
{
    case A:
    case B:
    case C:
    case D:
    case E:
    {
        printf("CASE E\n");
    }
        printf("Your case type = %s\n",caseType);
    break;
    default:
        printf("default\n");
    break;
}

Upvotes: 0

Views: 478

Answers (1)

Vlad Feinstein
Vlad Feinstein

Reputation: 11311

You would have to re-arrange your cases, so that the "special" one is on top - and then fall through:

switch(caseType)
{
    case E:
        printf("CASE E\n");
        // no break; here, fall through
    case A:
    case B:
    case C:
    case D:
        printf("Your case type = %s\n",caseType);
    break;
    default:
        printf("default\n");
    break;
}

Upvotes: 2

Related Questions