函数指针和必要性

Function pointers and necessity

我对用 C 语言破解微小的东西非常感兴趣。

函数指针:

据我所知,函数指针只不过是一个C变量,它将函数的地址指向一个普通的C变量。这样我们也可以使用指针调用函数。

问题:

  1. 使用函数指针而不是单独使用函数的必要性是什么?
  2. 它会做普通功能做不到的高级事情吗?

区别和用例与指针与常规对象基本相同。您可以存储指向函数的指针,并在编译 time/runtime 时配置将调用的函数。考虑最简单的例子 qsort:

void qsort( void *ptr, std::size_t count, std::size_t size,
            int (*comp)(const void *, const void *) );

只有一个 qsort 实现,但您可以使用不同的条件对相同的元素数组进行排序。

当你不知道在编译时使用什么函数时,你可以使用函数指针来解决那个问题。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef int (*fx)(int, int);
int one(int a, int b) { return a + b + 1; }
int two(int a, int b) { return a + b + 2; }
int three(int a, int b) { return a + b + 3; }
int four(int a, int b) { return a + b + 4; }

int main(void) {
    fx arfx[4] = {one, two, three, four};
    srand(time(0));
    for (int k = 0; k < 10; k++) {
        int n = rand() % 4; // 0, 1, 2, or 3
        int val = arfx[n](1, -1); // call one of functions in arfx
        printf("result is %d.\n", val);
    }
    return 0;
}

参见code running at ideone

Questions:

What is the necessity of using function pointers rather than using functions alone?

函数指针可以指向具有相同签名的各种函数,允许创建多态结构。它也可以作为回调 - 因此调用代码不需要知道可调用代码(可调用代码提供功能 - 依赖倒置原则)。

Will it do any advanced thing which a normal function cannot do?

您可以提供一个函数指针,作为一段不需要函数名来执行调用的代码的回调。其他地方提到的 qsort 就是一个很好的例子。

根据维基百科,“在计算机编程中,回调是对可执行代码或一段可执行代码的引用,它作为参数传递给其他代码。这允许较低级别的软件层调用较高级别中定义的子例程(或函数)。”

  1. 在 C 中,回调是使用函数指针实现的。例如,See this link.

  2. 普通函数可以将另一个函数作为其参数之一吗?从这个意义上讲,回调是一种高级事物,函数指针实现了它们。

此外,解释了另一个用例here