如何在 C 中实现函数查找表?

时间:2021-02-08 20:32:59

标签: c lookup-tables

假设我有一个程序,用户可以在其中选择 0-10 之间的数字。然后每个数字将对应于某个函数的调用。在 Python 中,我知道我可以创建一个函数名称数组,使用所选选项对其进行索引,然后调用该函数。我将如何在 C 中实现它?或者甚至有可能吗?

1 个答案:

答案 0 :(得分:4)

这是一个如何做的例子。请注意,所有函数都必须具有相同的签名,但当然您可以将其从我的 funptr 类型更改为例如具有 void 返回或采用 char 而不是两个的函数int 秒。

// 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);
}