切换到对所有情况执行相同的功能以及对其中一个情况执行单个打印语句

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

我有一个 switch case,在所有情况下都将执行相同的功能,但是对于其中一种情况,我还希望打印 print 语句。

我知道要对所有情况执行相同的功能,您需要执行以下操作:

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

在这种情况下,它将打印通过 caseType 传递的任何案例的案例类型。

但是,如果我想打印案例 A(如果案例 == A,以及 Your case type 打印?

我试过了,但它似乎没有按我想要的方式工作(假设 E 是通过的参数):

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;
}

您必须 re-arrange 您的案件,以便“特殊”案件在最上面 - 然后失败:

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;
}