Since functions exist as a block of memory, we may define pointers to functions as well as any other variable. However, before a pointer may point to a function, it must be defined as a pointer to a function of the correct type. Therefore functional types must be defined.
The type of a function is determined by:
the output type
the signature of the function's prototype
int f(int, char, float); int g(char, int); float h(int, char, float); float i(char, int);
Each of these functions is a different type of function because they have different signatures or different output types.
Now that function types have been defined, it is possible to define pointers to functions. If the functions f() and g() have prototypes as follows:
int f(int, char, float); float g(char, int);
then ptr_f and ptr_g may be pointers to these functions respectively if they are defined as follows:
int (* ptr_f ) ( int, char, float ); float (* ptr_g ) ( char, int);
Notice the parenthesis around the pointer name and the pointer definition operator inside of the parenthesis. The parentheses indicate that a function is involved and the pointer definition operator indicates that these pointers may point to a function.
Once the functions and the pointers have been defined, the pointer may be assigned the address of their respective functions by using either one of the following types of assignments:
ptr_f = &f;
ptr_g = g;
These two statements are syntactically equivalent because the & is not required. While this is true, the first of these two statements is preferred because it tips off the programmer reading the code what is going on.
Once the pointer ptr_f is defined, it could be used to replace the function name as the following:
ptr_f(an_int, a_float, a_char);
which is equivalent to
*ptr_f(an_int, a_float, a_char);
Notice that in the first case the indirection operator is not required. While these two statements are equivalent, the second of these is preferred because it tips off the programmer reading the code what is going on. See PTRTOFN.CPP
As discussed previously, pointers and arrays are closely linked. It is possible therefore to define an array of pointers to functions of the same type. For example:
outputtype (*ptr [SIZE] ) (signature);
would define an array of pointers to SIZE different functions. See MENUS.CPP
There are several interesting uses of pointers to functions. One use is that a pointer to a function can be used to pass one function into the body of another function. Functions as such may not be an argument of another function. However a pointer to a function may be passed into the body of another function. In this way this little inconvenience can be overcome.