views:

193

answers:

4

Hi all.. i am working in embedded C environment.. can we pass function pointer as an argument to a function in C? if so, can u give me a sample declaration and definition.. thnx in advance

+11  A: 

Definitely.

void f(void (*a)()) {
    a();
}

void test() {
    printf("hello world\n");
}

int main() {
     f(&test);
     return 0;
}
Mehrdad Afshari
Change the call to f(test);
Richard Pennington
Both will work. The ampersand is optional. So is dereferencing the pointer when you're calling the function pointer.
Mehrdad Afshari
True, there's no need to change anything. Moreover, even the "pointer" syntax in parameter declaration is optional. The above `f` could've been declared as `void f(void a())`.
AndreyT
Using a typedef for the function pointer type could make the code eaiser to read.
Loadmaster
+4  A: 

I suggest looking at the world-famous C faqs

lorenzog
+7  A: 

Let say you have function

int func(int a, float b);

So pointer to it will be

int (*func_pointer)(int, float);

So than you could use it like this

  func_pointer = func;
  (*func_pointer)(1, 1.0);

  /*below also works*/
  func_pointer(1, 1.0);

To avoid specifying full pointer type every time you need it you coud typedef it

typedef int (*FUNC_PTR)(int float);

and than use like any other type

void executor(FUNC_PTR func)
{ 
   func(1, 1.0);
}

int silly_func(int a, float b)
{ 
  //do stuff
}

main()
{
  FUNC_PTR ptr;
  ptr = silly_func;
  executor(ptr); 
  /* this should also wotk */
  executor(silly_func)
}

I suggest looking at the world-famous C faqs.

Michal Sznajder
A: 

Check qsort()

void qsort(void *base, size_t nmemb, size_t size,
           int (*compar)(const void *, const void *));

The last argument to the function is a function pointer. When you call qsort() in a program of yours, the execution "goes into the library" and "steps back into your own code" through the use of that pointer.

pmg