c - 如何在 C 中实现函数查找表?
问题描述
假设我有一个程序,用户可以在其中选择 0-10 之间的数字。然后每个数字将对应于某个函数的调用。在 Python 中,我知道我可以创建一个函数名称数组,使用所选选项对其进行索引,然后调用该函数。我将如何在 C 中实现这一点?或者甚至有可能吗?
解决方案
这是一个如何做到这一点的例子。请注意,所有函数必须具有相同的签名,但当然您可以将其从我的funptr
类型更改为例如具有void
return 或采用 achar
而不是两个int
s 的函数。
// Declare the type of function pointers.
// Here a function that takes two ints and returns an int.
typedef int (*funptr)(int, int);
// These are the two functions that shall be callable.
int f1(int a, int b) { return a + b; }
int f2(int a, int b) { return a - b; }
// The array with all the functions.
funptr functions[] = {
f1,
f2,
};
// The caller.
int call(int i, int a, int b)
{
return functions[i](a, b);
}
推荐阅读
- android - 添加视图不覆盖全屏
- reactjs - 为什么 useState 不替换旧值?
- windows - VB 6 - 移除/隐藏系统关机计数器| 关闭外壳命令
- performance - Chrome:加载时在网站上冻结 2 秒
- bash - 如何使用 bash/sed 循环数字并延迟启动多个程序
- node.js - 在 AWS Lambda 上执行 nodejs-traceroute 模块时出现“spawn traceroute ENOENT”错误
- javascript - 如何通过 ethplorer 获取 USDT 余额
- elasticsearch - Elasticsearch - 如何以高亮返回所有片段
- google-sheets - 所有基于时间的触发器似乎同时运行
- node.js - 如何在 nodejs 上多次托管网站?