替代 C 中的许多 case switch 语句 [英] Alternative to many case switch statement in C
问题描述
我有一个 8 位字节,代表 8 个物理交换机的状态.我需要为每次打开和关闭的开关排列做一些不同的事情.我的第一个想法是写一个 256 case switch 语句,但很快打字就变得乏味了.
I have a 8 bit byte that represents the states of 8 physical switches. I need to do something different for each permutation of switches being on and off. My first idea was to write a 256 case switch statement, but it quickly became tedious to type.
有没有更好的方法来做到这一点?
Is there a better way to do this?
我应该对功能更清楚一些.我有 8 个按钮,每个按钮都做一件事.我需要能够检测是否同时按下了多个开关,以便我可以同时运行这两个功能.
I should have been a bit clearer on the functions. I have 8 buttons that each do one thing. I need to be able to detect if multiple switches are pressed at once so I can run both functions at the same time.
推荐答案
您可以使用函数指针数组.小心用正值索引它 - char
可能会被签名.这是否比使用 switch
语句更乏味是有争议的 - 但执行肯定会更快.
You can use an array of function pointers. Be careful to index it by a positive value - a char
might be signed. Whether this is any more tedious than using a switch
statement is arguable - but execution will certainly be quicker.
#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;
}
这篇关于替代 C 中的许多 case switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!