Like other pointers, function pointers can be passed as arguments to functions. Normally, in fact, this is the only reason to use a function pointer.
The FUNCPTR.C program in the previous section is easy to follow but not very practical. In a real program, you wouldn't go to the trouble of creating a function pointer just to call printf from the main function.
The FUNCPTR1.C program demonstrates how to pass a function pointer as an argument. It has a function named gimme_func that expects to be passed a function pointer:
/* FUNCPTR1.C: Passing function pointers as arguments. */
#include <stdio.h>
void gimme_func( void (*func_ptr) () );
main()
{
gimme_func( puts );
gimme_func( printf );
}
void gimme_func( void (*func_ptr) () )
{
(*func_ptr) ( "Ausgezeichnet!" );
}
Here is the output from FUNCPTR1.C:
Ausgezeichnet!
Ausgezeichnet!
In the interests of brevity, the function gimme_func does a very simple job. It expects to receive a pointer to a function that can display a string and uses that pointer to print the string. The first call to gimme_func passes a pointer to the library function puts, and the second passes a pointer to printf.
Since the declaration of gimme_func states it takes a pointer to a function, the address-of operator is optional in a call to gimme_func. The following statements are equivalent:
gimme_func( puts );
gimme_func( &puts );