Reputation: 2661
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.
Upvotes: 0
Views: 254
Reputation: 325
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.
Upvotes: 1
Reputation: 461
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
{
// ...
}
}
Upvotes: 3