Pointers to Functions

Examine the program named FUNCPNT.CPP for an example of using a pointer to a function.

Output of the C++ Program

It must be pointed out that there is nothing new here, the pointer to a function is available in ANSI-C as well as in C++ and works in the manner described here for both languages. It is not regularly used by most C programmers, so it is defined here as a refresher. If you are comfortable with the use of pointers to functions, you can skip this discussion entirely.

There is nothing unusual about this program except for the pointer to a function declared in line 7. This declares a pointer to a function which returns nothing (void) and requires a single formal parameter, a float type variable. You will notice that all three of the functions declared in lines 4 through 6 fit this profile and are therefore candidates to be called with this pointer. If you have not used prototyping in C, these lines will look strange to you. Don’t worry about them at this point since we will study prototyping in the next chapter of this tutorial.

Observe that in line 14 we call the function print_stuff() with the parameter pi and in line 15 we assign the function pointer named function_pointer the value of print_stuff() and use the function pointer to call the same function again in line 16. Lines 14 and 16 are therefore identical in what is accomplished because of the pointer assignment in line 15. In lines 17 through 22, a few more

illustrations of the use of the function pointer are given. You will be left to study these on your own.

Since we assigned the name of a function to a function pointer, and did not get an assignment error, the name of a function must be a pointer to that function. This is exactly the case. A function name is a pointer to that function, but it is a pointer constant and cannot be changed. This is exactly the case we found when we studied arrays in ANSI-C at some point in our C programming background. An array name is a pointer constant to the first element of the array.

Since the name of the function is a constant pointer to that function, we can assign the name of the function to a function pointer and use the function pointer to call the function. The only caveat is that the return value and the number and types of parameters must be identical. Most C and C++ compilers will not, and in fact, can not warn you of type mismatches between the parameter lists when the assignments are made. This is because the assignments are done at run time when no type information is available to the system, rather than at compile time when all type information is available.

The use and operation of pointers must be thoroughly understood when we get to the material on dynamic binding and polymorphism later in this tutorial. It will be discussed in detail at that time.