Is it possible pass a function as a parameter in C? [duplicate]
Possible Duplicate:
How do you pass a function as a parameter in C?
Is it possible pass a function as a parameter in C? If yes, how?
No, you can't pass a 'function' as a parameter. You can, however, pass a pointer to a function instead.
When you reference a function by name without the parentheses for a function invocation, you are referencing a pointer to a function. Thus, for example, we could consider a function that generates a table of values for a mathematical 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);
}
Here, the functions 'sin()', 'cos()', and 'sqrt()' all have the same prototype schema: function taking a double argument and returning a double value. Note that if I mistakenly wrote:
generator(0.0, 1.0, 0.02, sin());
I would get a bunch of compilation errors - one because 'sin()' expects an argument, and another because 'generator()' expects a pointer to a function and not a double value as the last argument.
(Also note that a good program would at least identify the function it is calculating, and the repeated increments of a double number is not a good idea for accuracy. It is but an example.)
Use a pointer to function.
Like int (*ptr2_fun)()
Receiving function being:
int execute_your_function(int (*fun)())
Here you have some examples
Use function pointers
Yes. Not a function per se but a pointer to a function instead.
See qsort()
.
int cmp(const void *a, const void *b) { /* ... */ }
/* ... */
qsort(data, nelems, sizeof *data, cmp); /* pass the function `cmp` to qsort() */
Great function pointer tutorial here:
http://www.newty.de/fpt/index.html
Sure, you can use a function pointer.
#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;
}
精彩评论