C Language Function Pointers Introduction


Example

Just like char and int, a function is a fundamental feature of C. As such, you can declare a pointer to one: which means that you can pass which function to call to another function to help it do its job. For example, if you had a graph() function that displayed a graph, you could pass which function to graph into graph().

// A couple of external definitions to make the example clearer
extern unsigned int screenWidth;
extern void plotXY(double x, double y);

// The graph() function.
// Pass in the bounds: the minimum and maximum X and Y that should be plotted.
// Also pass in the actual function to plot.
void graph(double minX, double minY,
           double maxX, double maxY,
           ???? *fn) {            // See below for syntax

    double stepX = (maxX - minX) / screenWidth;
    for (double x=minX; x<maxX; x+=stepX) {

        double y = fn(x);         // Get y for this x by calling passed-in fn()

        if (minY<=y && y<maxY) {
            plotXY(x, y);         // Plot calculated point
        } // if
    } for
} // graph(minX, minY, maxX, maxY, fn)

Usage

So the above code will graph whatever function you passed into it - as long as that function meets certain criteria: namely, that you pass a double in and get a double out. There are many functions like that - sin(), cos(), tan(), exp() etc. - but there are many that aren't, such as graph() itself!

Syntax

So how do you specify which functions you can pass into graph() and which ones you can't? The conventional way is by using a syntax that may not be easy to read or understand:

double (*fn)(double); // fn is a pointer-to-function that takes a double and returns one

The problem above is that there are two things trying to be defined at the same time: the structure of the function, and the fact that it's a pointer. So, split the two definitions! But by using typedef, a better syntax (easier to read & understand) can be achieved.