arrays - 在 C 语言中使用数组声明类似的函数
问题描述
如何使用数组来声明类似的函数?我想节省一些空间。下面是一个例子:
void checkEntered1(int button){
if (entered[0] != 0){
checkEntered2(button);
}
}
void checkEntered2(int button){
if (entered[1] != 0){
checkEntered3(button);
}
}
void checkEntered3(int button){
if (entered[2] != 0){
checkEntered4(button);
}
}
void checkEntered4(int button){
if (entered[3] != 0){
checkEntered5(button);
}
}
下面的工作吗?这是一个有效的声明吗?
for (int i=1; i<=4; i++){
void checkEntered[i](int button){
if (entered[i-1] != 0){
checkEntered[i+1](button);
}
}
}
解决方案
我猜你需要一个函数指针数组。
void dispatch_button(int button) {
typedef void button_handler_t(int);
static button_handler_t* handlers[] = { checkEntered1, checkEntered2, ... };
size_t n_handlers = sizeof handlers / sizeof handlers[0];
for (size_t i = 0; i < n_handlers; ++i)
if (entered[i] == 0) {
handlers[i](button);
return;
}
// error when no handler was found
}
推荐阅读
- java - 从 SQL Server 读取 nvarchar 时带菱形的问号
- amazon-web-services - 在客户端的防火墙上使用列入白名单的 IP 地址
- sql - 如何编写 SQL 查询以获取每个动物园中第二重的动物?
- c# - C# .NET 检查应用程序是否通过 Open With 由文件打开
- r - 闪亮的应用程序中的ggplotly不断崩溃(Rstudio)
- sql - 在“where”子句中使用平均值
- javascript - react-image-gallery 中的样式标题
- nginx - Nginx 设置,url 参数被忽略
- php - 如何将 mb_convert_encoding 中的单个 Unicode 值转换为整数
- sql-server - SQL Server,一列的批量更新