A Little C Primer/Pointers to C Functions

This document has explained how to declare pointers to variables, arrays, and structures in C. It is also possible to define pointers to functions. This feature allows functions to be passed as arguments to other functions. This is useful for, say, building a function that determines solutions to a range of math functions.

The syntax for declaring pointers to functions is obscure, and so let's start with an oversimplified example: declaring a pointer to the standard library function "printf()":

   /* ptrprt.c */

   #include <stdio.h>

   void main()
   {
     int (*func_ptr) ();                  /* Declare the pointer. */
     func_ptr = printf;                   /* Assign it a function. */
     (*func_ptr) ( "Printf is here!\n" ); /* Execute the function. */
   }

The function pointer has to be declared as the same type ("int" in this case) as the function it represents.

Next, let's pass function pointers to another function. This function will assume the functions passed to it are math functions that accept double and return double values:

   /* ptrroot.c */

   #include <stdio.h>

   #include <math.h>
   
   void testfunc ( char *name, double (*func_ptr) () );
   
   void main()
   {
     testfunc( "square root", sqrt );
   }
   
   void testfunc ( char *name, double (*func_ptr) () )
   {
     double x, xinc;
     int c;
   
     printf( "Testing function %s:\n\n", name );
     for( c=0; c < 20; ++c )
     {
       printf( "%d: %f\n", c,(*func_ptr)( (double)c ));
     }
   }

It is obvious that not all functions can be passed to "testfunc()". The function being passed must agree with the expected number and type of parameters, as well as with the value returned.