如何在函数实现中使用函数的函数参数?

How to use a function argument of a function in the function implementation?

如果我有这样的声明:

int foo1 (int foo2 (int a));

如何实现这个 foo1 功能?喜欢,

int foo1 (int foo2 (int a))
{
    // How can I use foo2 here, which is the argument?
}

以及如何在 main 中调用 foo1 函数?喜欢:

foo1(/* ??? */);

当您将函数参数声明为函数时,编译器会自动将其类型调整为"pointer to function"。

int foo1 (int foo2 (int a))

完全一样
int foo1 (int (*foo2)(int a))

(这类似于将函数参数声明为数组(例如 int foo2[123])如何自动使其成为指针(例如 int *foo2)。)

至于如何使用 foo2:您可以调用它(例如 foo2(42))或者您可以取消引用它(*foo2),这(与函数一样)立即再次衰减回指针(然后您可以调用(例如 (*foo2)(42))或再次取消引用(**foo2),它立即衰减回指针,...)。

要调用foo1,您需要向其传递一个函数指针。如果周围没有现成的函数指针,可以定义一个新的函数(在main之外),如:

int bar(int x) {
    printf("hello from bar, called with %d\n", x);
    return 2 * x;
}

那你可以做

foo1(&bar);  // pass a pointer to bar to foo1

或等效

foo1(bar);  // functions automatically decay to pointers anyway

或许,这个简单的例子可以帮到您:

#include <stdio.h>

int foo1 (int foo2 (int),int i);
int sub_one (int);
int add_one (int);

int main() {
    int i=10,j;
    j=foo1(sub_one,i);
    printf("%d\n",j);
    j=foo1(add_one,i);
    printf("%d\n",j);
}

int sub_one (int i) {
    return i-1;
}
int add_one (int i) {
    return i+1;
}

int foo1 (int foo2 (int),int i) {
    return foo2(i);
}

看看下面的代码,它展示了如何按照您想要的方式调用函数。

 #include <stdio.h>


/* Declaration of foo1 . It receives a specific function pointer foo2 and an integer. */
int foo1 (int (*foo2)(int), int a);

int cube(int number)
{
    return (number * number * number);
}

int square(int number)
{
    return (number * number);
}

int foo1 (int (*foo2)(int), int a)
{
    int ret;

    /* Call the foo2 function here. */
    ret = foo2(a);

    printf("Result is: %d\r\n", ret);

    return (ret);
}

int main()
{
    int a = 3;

    foo1(square, a);
    foo1(cube, a);

    return 0;
}