【问题标题】:is it possible pass a function as a parameter in c? [duplicate]是否可以在c中将函数作为参数传递? [复制]
【发布时间】:2010-12-14 10:03:35
【问题描述】:

可能重复:
How do you pass a function as a parameter in C?

是否可以在 c 中将函数作为参数传递?如果是怎么办?

【问题讨论】:

标签: c


【解决方案1】:

不,您不能将“函数”作为参数传递。但是,您可以改为传递指向函数的指针。

当您在函数调用中按名称引用函数而不带括号时,您正在引用指向函数的指针。因此,例如,我们可以考虑一个为数学函数生成值表的函数:

#include <math.h>
#include <stdio.h>

static void generator(double lo, double hi, double inc, double (*function)(double))
{
    double x;
    for (x = lo; x < hi; x += inc)
        printf("x = %6g; f(x) = %6g\n", x, (*function)(x))
}

int main(void)
{
     generator(0.0, 1.0, 0.02, sin);
     generator(0.0, 1.0, 0.02, cos);
     generator(0.0, 1.0, 0.02, sqrt);
     return(0);
}

这里,函数 'sin()'、'cos()' 和 'sqrt()' 都具有相同的原型模式:函数接受一个 double 参数并返回一个 double 值。请注意,如果我写错了:

generator(0.0, 1.0, 0.02, sin());

我会得到一堆编译错误 - 一个是因为 'sin()' 需要一个参数,另一个是因为 'generator()' 需要一个指向函数的指针,而不是作为最后一个参数的双精度值。

(另请注意,一个好的程序至少会识别它正在计算的函数,而双数的重复递增对于准确性来说并不是一个好主意。这只是一个例子。)

【讨论】:

    【解决方案2】:

    是的。不是函数本身,而是指向函数的指针。

    见qsort()。

    int cmp(const void *a, const void *b) { /* ... */ }
    /* ... */
    qsort(data, nelems, sizeof *data, cmp); /* pass the function `cmp` to qsort() */
    

    【讨论】:

      【解决方案3】:

      当然,你可以使用函数指针。

      #include <stdio.h>
      typedef void (*bar_callback)(void);
      
      void foo(void)
      {
        puts("foo");
      }
      
      void bar(bar_callback callback)
      {
        puts("bar");
        callback();
      }
      int main(int argc,char **argv)
      {
        bar(foo);
        return 0;
      }
      

      【讨论】:

        【解决方案4】:

        这里有很棒的函数指针教程:

        http://www.newty.de/fpt/index.html

        【讨论】:

          【解决方案5】:

          【讨论】:

            【解决方案6】:

            使用指向函数的指针。
            喜欢int (*ptr2_fun)() 接收函数为:
            int execute_your_function(int (*fun)())

            这里有一些examples

            【讨论】:

            • 检查 qsort()。它接受一个比较函数。
            猜你喜欢
            • 2014-04-15
            • 2020-02-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-10-20
            • 2010-10-05
            • 1970-01-01
            相关资源
            最近更新 更多