可能是重复问题:
如何在C语言中将函数作为参数传递?
在C语言中,是否可以将函数作为参数传递?如果可以,该如何操作?
可能是重复问题:
如何在C语言中将函数作为参数传递?
在C语言中,是否可以将函数作为参数传递?如果可以,该如何操作?
不,你不能将“function”作为参数传递。但是,你可以传递函数的指针。
当你在没有用括号调用函数时通过名称引用函数时,你引用的是一个函数的指针。例如,我们可以考虑一个生成数学函数值表的函数:
#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);
}
generator(0.0, 1.0, 0.02, sin());
使用函数指针。
像 int (*ptr2_fun)()
这样。
接收函数为:
int execute_your_function(int (*fun)())
这里有一些示例
参见qsort()
。
int cmp(const void *a, const void *b) { /* ... */ }
/* ... */
qsort(data, nelems, sizeof *data, cmp); /* pass the function `cmp` to qsort() */
#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;
}