A function pointer is like any other pointer, but it points to the address of a function instead of the address of data (on heap or stack). Like any pointer, it needs to be typed correctly. Functions are defined by their return value and the types of parameters they accept. So in order to fully describe a function, you must include its return value and the type of each parameter is accepts. When you typedef such a definition, you give it a 'friendly name' which makes it easier to create and reference pointers using that definition.
So for example assume you have a function:
float doMultiplication (float num1, float num2 ) {
return num1 * num2; }
then the following typedef:
typedef float(*pt2Func)(float, float);
can be used to point to this doMulitplication
function. It is simply defining a pointer to a function which returns a float and takes two parameters, each of type float. This definition has the friendly name pt2Func
. Note that pt2Func
can point to ANY function which returns a float and takes in 2 floats.
So you can create a pointer which points to the doMultiplication function as follows:
pt2Func *myFnPtr = &doMultiplication;
and you can invoke the function using this pointer as follows:
float result = (*myFnPtr)(2.0, 5.1);
This makes good reading: http://www.newty.de/fpt/index.html