[英]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
我想知道是否可以在这里使用switch,尤其是对于
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: 请注意,您的示例应在函数输入时检查
reply
-Pointer:
void handleGenieEvent (struct genieReplyStruct *reply)
{
if (NULL == reply)
{
// report error
return;
}
else
{
// ...
}
}
In this case you should use brackets and the break statement: 在这种情况下,应使用方括号和break语句:
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-else代码段具有相同的功能,则需要break语句。 If you miss the breaks and got case 0 for example, case 1 and 2 will execute as well.
例如,如果您错过休息时间并获得案例0,则案例1和2也将执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.