Previous: 14.3 Pointers to Functions
Up: 14.3 Pointers to Functions
Previous Page: 14.3 Pointers to Functions
Next Page: 14.4 Summary

14.3.1 Function Pointers as Returned Values

It is also possible for functions to return a function pointer as a value. This ability increases the flexibility of programs. We will use a simple example to implement a function that returns a function pointer. The example is merely illustrative, and it would be easy to write a program to perform the same task without the use of a function pointer. Let us define a type, which is a pointer to a function that returns an integer.

typedef int (*PFI)();
We can now use PFI as a data type in declaring variables, parameters, and returned values.

Our example program repeatedly reads an integer until EOF. If an integer is odd, the program computes its cube; otherwise, the program computes its square. For each integer, we call a function evenodd() which returns a function pointer either to icube() or to isquare() depending on whether the integer is odd or even. The function pointer returned by evenodd() and the integer itself are both passed to a function process(), which applies the dereferenced function pointer to the integer. The result is then printed. Figure 14.18 shows the program driver.

For each integer, the program calls evenodd() to get a returned function pointer which is assigned to fptr. Then, it calls process() to apply (*fptr) to x. The result is then printed. Let us now write the function evenodd() that takes an integer as an argument. If the argument is odd, the function returns a pointer to icube(); otherwise, it returns a pointer to isquare(). The function evenodd(), together with functions process() and icube() are also shown in Figure 14.18.

When the program files fptr.c and sumutil.c are compiled and linked, the sample session is:

Using function pointers as parameters we can write generic functions. By returning function pointers, the called functions can select the functions that must be used in different circumstances. Function pointers help make a program compact as well as intelligent.



Previous: 14.3 Pointers to Functions
Up: 14.3 Pointers to Functions
Previous Page: 14.3 Pointers to Functions
Next Page: 14.4 Summary

tep@wiliki.eng.hawaii.edu
Sat Sep 3 07:21:51 HST 1994