你如何在C中将函数作为参数传递? [英] How do you pass a function as a parameter in C?

查看:35
本文介绍了你如何在C中将函数作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,该函数对一组数据执行通过参数传递的函数.在 C 中如何将函数作为参数传递?

I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?

推荐答案

声明

带有函数参数的函数原型如下所示:

A prototype for a function which takes a function parameter looks like the following:

void func ( void (*f)(int) );

这表明参数 f 将是一个指向函数的指针,该函数具有 void 返回类型并采用单个 int 参数.以下函数 (print) 是一个可以作为参数传递给 func 的函数示例,因为它是正确的类型:

This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:

void print ( int x ) {
  printf("%d
", x);
}

函数调用

使用函数参数调用函数时,传递的值必须是指向函数的指针.为此使用函数名称(不带括号):

When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:

func(print);

将调用 func,将打印函数传递给它.

would call func, passing the print function to it.

函数体

与任何参数一样,func 现在可以在函数体中使用参数的名称来访问参数的值.假设 func 将应用它传递给数字 0-4 的函数.首先考虑一下直接调用 print 的循环会是什么样子:

As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:

for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
  print(ctr);
}

由于func 的参数声明表示f 是指向所需函数的指针的名称,我们首先回忆一下如果f是一个指针,然后 *ff 指向的东西(即函数 print 在这种情况下).因此,只需用 *f 替换上面循环中出现的每次打印:

Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:

void func ( void (*f)(int) ) {
  for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
    (*f)(ctr);
  }
}

来源

这篇关于你如何在C中将函数作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆