Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible pass a function as a parameter in c? [duplicate]

Tags:

c

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?

like image 916
Hannoun Yassir Avatar asked Nov 27 '22 08:11

Hannoun Yassir


2 Answers

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.)

like image 77
Jonathan Leffler Avatar answered Dec 15 '22 08:12

Jonathan Leffler


Use a pointer to function.
Like int (*ptr2_fun)() Receiving function being:
int execute_your_function(int (*fun)())

Here you have some examples

like image 34
Arkaitz Jimenez Avatar answered Dec 15 '22 09:12

Arkaitz Jimenez