c - 为什么函数指针有用?

标签 c function pointers

所以,我正在查看函数指针,在我看到的示例中,特别是在这个答案 here 中。它们看起来相当多余。

例如,如果我有以下代码:

int addInt(int n, int m) {
    return n+m;
}
int (*functionPtr)(int,int);
functionPtr = &addInt;
int sum = (*functionPtr)(2, 3); // sum == 5

看来创建函数指针没有任何目的,直接这样做不是更容易吗?

int sum = addInt(2, 3); // sum == 5

如果是这样,那么您为什么需要使用它们,它们的用途是什么? (以及为什么需要将函数指针传递给其他函数)

最佳答案

简单的指针示例似乎同样毫无用处。当你开始做更复杂的事情时,它会有所帮助。例如:

// Elsewhere in the code, there's a sum_without_safety function that blindly
// adds the two numbers, and a sum_with_safety function that validates the 
// numbers before adding them.

int (*sum_function)(int, int);
if(needs_safety) {
    sum_function = sum_with_safety;
}
else {
    sum_function = sum_without_safety;
}
int sum = sum_function(2, 3);

或者:

// This is an array of functions. We'll choose which one to call based on 
// the value of index.
int (*sum_functions)(int, int)[] = { ...a bunch of different sum functions... };
int (*sum_function)(int, int) = sum_functions[index];
int sum = sum_function(2, 3);

或者:

// This is a poor man's object system. Each number struct carries a table of 
// function pointers for various operations; you can look up the appropriate 
// function and call it, allowing you to sum a number without worrying about
// exactly how that number is stored in memory.

struct number {
    struct {
        int (*sum)(struct number *, int);
        int (*product)(struct number *, int);
        ...
    } * methods;
    void * data;
};

struct number * num = get_number();
int sum = num->methods->sum(number, 3);

最后一个示例基本上是 C++ 如何执行虚拟成员函数的。将方法结构替换为哈希表,您就拥有了 Objective-C 的方法分派(dispatch)。与变量指针一样,函数指针可以让您以有值(value)的方式抽象事物,从而使代码更加紧凑和灵活。然而,从最简单的例子来看,这种力量并不明显。

关于c - 为什么函数指针有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19215705/

相关文章:

c - 从 C 中的字符串中删除子字符串

python - 在Python函数中使用递归输出元组列表

c++ - 将指向结构的指针转换为具有较少数量字段的另一种结构类型

c - 如何在c中过滤数组?

c - 如何正确传递涉及指针的数组?

javascript - 如何将输入的值插入到JS中的另一个输入?

css - 如何从 functions.php 将以下 css 代码添加到我的页眉中?

c++ - c++中以下类似的语句有区别吗?

c++ - 复制特定类时崩溃

c - ptrace 读取子进程中的 errno 值