替代C中的许多case switch语句

时间:2015-03-27 21:02:59

标签: c arduino switch-statement

我有一个8位字节,表示8个物理开关的状态。我需要为开关的每个排列打开和关闭做一些不同的事情。我的第一个想法是写一个256 case switch语句,但输入很快就变得乏味了。

有更好的方法吗?

编辑:我应该对这些功能更清楚一点。我有8个按钮,每个按钮都做一件事。我需要能够检测是否同时按下多个开关,这样我就可以同时运行这两个功能。

2 个答案:

答案 0 :(得分:3)

您可以使用函数指针数组。小心将其索引为正值 - 可能会签署char。这是否比使用switch语句更乏味是有争议的 - 但执行肯定会更快。

#include <stdio.h>

// prototypes
int func00(void);
int func01(void);
...
int funcFF(void);

// array of function pointers
int (*funcarry[256])(void) = {
    func00, func01, ..., funcFF
};

// call one function
int main(void){
    unsigned char switchstate = 0x01;
    int res = (*funcarry[switchstate])();
    printf ("Function returned %02X\n", res);
    return 0;
}

// the functions
int func00(void) {
    return 0x00;
}
int func01(void) {
    return 0x01;
}
...
int funcFF(void) {
    return 0xFF;
}

答案 1 :(得分:2)

您可以定义一个函数数组,并将该字节用作数组中的索引,并相应地在数组中的给定位置调用该函数。

相关问题