简体   繁体   中英

How do I use switch with structs in C

Hi I have the following code snippet from 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);
}

And I am wondering if it's possible to use switch here, especially for the index

I tried this:

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

but that doesn't work.

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

will work.

Please note that your sample should check the reply -Pointer upon function entry:

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

In this case you should use brackets and the break statement:

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

If you want the same funcitonality as the if-else code snippet above, you need the break statements. If you miss the breaks and got case 0 for example, case 1 and 2 will execute as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM