ProAnswers.org

How do you pass a function as a parameter in C?

A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior.

The syntax for declaring a function pointer might seem messy at first, but in most cases it's really quite straight-forward once you understand what's going on. Let's look at a simple example:

void (*foo)(int);

[b]Reading Function Pointer Declarations:[/b]



In this example, foo is a pointer to a function taking one argument, an integer, and that returns void. It's as if you're declaring a function called "*foo", which takes an int and returns void; now, if *foo is a function, then foo must be a pointer to a function.

void *(*foo)(int *);

Here, the key is to read inside-out; notice that the innermost element of the expression is *foo, and that otherwise it looks like a normal function declaration. *foo should refer to a function that returns a void * and takes an int *. Consequently, foo is a pointer to just such a function.



 



Initializing Function Pointers

To initialize a function pointer, you must give it the address of a function in your program. The syntax is like any other variable:

#include
void my_int_func(int x)
{
printf( "%d
", x );
}

int main()
{
void (foo)(int);
/
the ampersand is actually optional */
foo = &my_int_func;

return 0;

}

[b]Using a Function Pointer[/b]

To call the function pointed to by a function pointer, you treat the function pointer as though it were the name of the function you wish to call. The act of calling it performs the dereference; there's no need to do it yourself:

#include
void my_int_func(int x)
{
printf( "%d
", x );
}

int main()
{
void (*foo)(int);
foo = &my_int_func;

/* call my_int_func (note that you do not need to write (*foo)(2) ) */
foo( 2 );
/* but if you want to, you may */
(*foo)( 2 );

return 0;

}

Note that function pointer syntax is flexible; it can either look like most other uses of pointers, with & and *, or you may omit that part of syntax. This is similar to how arrays are treated, where a bare array decays to a pointer, but you may also prefix the array with & to request its address.