如何在C中使用带结构的开关

时间:2016-01-19 23:07:16

标签: c struct switch-statement

您好我有here的以下代码段:

void handleGenieEvent(struct genieReplyStruct *reply) {
    if (reply->cmd != GENIE_REPORT_EVENT) {
        printf("Invalid event from the display: 0x%02X\r\n", reply->cmd) ;
        return;
    }    
    /**/
    if (reply->object == GENIE_OBJ_KEYBOARD) {
        if (reply->index == 0)  // Only one keyboard
            calculatorKey(reply->data);
        else
            printf("Unknown keyboard: %d\n", reply->index);
    } else
    if (reply->object == GENIE_OBJ_WINBUTTON) {
        /**/
        if (reply->index == 1) {    // Clock button on main display
            //do smth
        } else
        if (reply->index == 2) {
            //do smth
        } else
        if (reply->index == 0) { // Calculator button on clock display
            //do smth
        } else
            printf("Unknown button: %d\n", reply->index);
    } else
        printf("Unhandled Event: object: %2d, index: %d data: %d [%02X %02X %04X]\r\n",
      reply->object, reply->index, reply->data, reply->object, reply->index, reply->data);
}

我想知道是否可以在此处使用切换,尤其是index

我试过了:

switch (reply->index)
    case 0:
        //do smth
    case 1: 
        //do smth
    case 2: 
        //do smth

但这不起作用。

2 个答案:

答案 0 :(得分:3)

switch (reply->index)
{
    case 0:
      //do smth
        break;
    case 1: 
     //do smth
        break;
    case 2: 
     //do smth
        break;
    default:
        printf("Unknown button: %d\n", reply->index);
        break;
}

会奏效。

请注意,您的样本应在功能输入时检查reply - 指针:

void handleGenieEvent (struct genieReplyStruct *reply)
{
    if (NULL == reply)
    {
        // report error
        return;
    }
    else
    {
        // ...
    }
}

答案 1 :(得分:1)

在这种情况下,您应该使用括号和break语句:

switch (reply->index){ <---bracket
    case 0:
        //do smth
        break;
    case 1: 
        //do smth
        break;
    case 2: 
        //do smth
        break;
}<---bracket

如果你想要与上面的if-else代码片段相同的功能,你需要break语句。例如,如果你错过了中断并得到了案例0,那么案例1和2也会执行。