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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With