用C中的函数指针定义和调用高阶函数组合函数

问题描述 投票:0回答:1

function types上的Wikipedia文章列出了“高阶函数组合函数”的有趣声明:

int (*compose(int (*f)(int), int (*g)(int)))(int);

作为一项学习练习,我想在测试程序中实现它,但是失败了,编译器抛出了许多警告和错误。我的尝试:

int a(int x) {
    return x + 1;
}

int b(int x) {
    return x * 2;
}

int (*compose(int (*f)(int y), int (*g)(int z)))(int x) {
    return (*f)(x) - (*g)(x);
}

int main(void) {
    int x = 5;
    int r = (*compose)((*a)(x), (*b)(x))(x);
    printf("Compose result for x = %d: %d\n", x, r);

    return 0;
}

我很高兴解释维基百科的声明与f(g(h(x)))这样的简单函数组成有何不同,以及如何实现它,最好是使用类似于我的简单程序。

c function function-pointers function-composition
1个回答
3
投票

这里有一些问题要解决...:

  • 在C语言中,您无法在运行时动态组成函数;仅在编译时静态地进行。
  • 在C中,当使用函数的标识符(已经定义)时-类型实际上已经是函数指针,即,“调用运算符”(或“括号运算符”)始终适用于函数指针。
  • 您的语法有点不正确。

尝试对您的代码进行此修改:

#include <stdio.h> 

int a(int x) {
    return x + 1;
}

int b(int x) {
    return x * 2;
}

int compose(int (*f)(int y), int (*g)(int z), int x) {
    return f(x) - g(x);
}

int main(void) {
    int x = 5;
    int r = compose(a, b, x);
    printf("Compose result for x = %d: %d\n", x, r);

    return 0;
}

compiles

© www.soinside.com 2019 - 2024. All rights reserved.