5

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Hannoun Yassir
  • 20,583
  • 23
  • 77
  • 112
  • 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
  • 22,500
  • 11
  • 75
  • 105
9

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
  • 730,956
  • 141
  • 904
  • 1,278
6

Use function pointers

Naveen
  • 74,600
  • 47
  • 176
  • 233
4

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
  • 106,608
  • 13
  • 126
  • 198
3

Great function pointer tutorial here:

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

user204884
  • 1,745
  • 2
  • 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
  • 223,662
  • 58
  • 417
  • 506