【问题标题】:How can I implement a function lookup table in C?如何在 C 中实现函数查找表?
【发布时间】:2021-05-12 11:47:28
【问题描述】:

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

【问题讨论】:

  • 您可以创建一个指向函数的指针数组。
  • 查找函数指针

标签: c lookup-tables


【解决方案1】:

我在上面的解决方案中看到的唯一问题是没有检查数组索引(您可能会遇到一些棘手的问题)。 为了使代码更健壮,您可以添加对索引(边界)的检查,例如

  • 在函数“call”中添加一个 if 语句,您可以在其中检查参数 i(不大于最大值)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 如果您开始需要花哨的、多种类型的函数签名,那么您可以让您的函数采用结构或指向结构的指针,这些结构定义了输入和输出参数和类型。这些结构最终开始描述抽象语法树 (AST)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 2017-03-25
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多