4

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 ?

Community
  • 1
  • 1
Hannoun Yassir
  • 19,642
  • 23
  • 75
  • 111
  • 2
    Duplicate of http://stackoverflow.com/questions/9410/how-do-you-pass-a-function-as-a-parameter-in-c – quamrana Nov 08 '09 at 18:10

6 Answers6

9

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

Here you have some examples

Arkaitz Jimenez
  • 21,514
  • 11
  • 73
  • 100
8

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

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
5

Use function pointers

Naveen
  • 71,879
  • 44
  • 171
  • 229
3

Great function pointer tutorial here:

http://www.newty.de/fpt/index.html

user204884
  • 1,705
  • 1
  • 19
  • 27
3

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;
}
nos
  • 215,098
  • 54
  • 400
  • 488
3

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() */
pmg
  • 103,426
  • 11
  • 122
  • 196