简体   繁体   English

如何在 C 中实现 function 查找表?

[英]How can I implement a function lookup table in C?

Say I had a program where the user could select a number between 0-10.假设我有一个程序,用户可以在其中 select 一个介于 0-10 之间的数字。 Each number would then correspond to the calling of a certain function.然后每个数字将对应于某个 function 的调用。 In Python, I know I could just create an array of function names, index into it with the selected option, and then call the function.在 Python 中,我知道我可以创建一个 function 名称的数组,使用所选选项对其进行索引,然后调用 function。 How would I implement this in C?我将如何在 C 中实现这一点? Or is it even possible?或者甚至有可能吗?

Here is an example how to do it.这是一个如何做到这一点的例子。 Please note that all functions must have the same signature, but of course you can change that from my funptr type to for example a function that has void return or takes a char and not two int s.请注意,所有函数必须具有相同的签名,但当然您可以将其从我的funptr类型更改为例如具有void return 或采用char而不是两个int的 function 。

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

The only problem that I can see in the solution from above is that there is no check for the array index (you may get some tricky problems).我在上面的解决方案中看到的唯一问题是没有检查数组索引(您可能会遇到一些棘手的问题)。 To make the code more robust, you can add a check for the index (boundaries), like为了使代码更健壮,您可以添加对索引(边界)的检查,例如

  • add one if statement inside of function "call" where you check the parameter i (not to be bigger than the maximum value)在 function "call" 中添加一个 if 语句,在其中检查参数 i(不大于最大值)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM