Programming and Graphics

(Kiana) #1

5.5 Pointers to functions 143


Assume that we need to call a function A which, in turn, calls either
function B or function C. We want the call to A to include an argument that
allows us to specify which one of the functions B or C will be called. This can
be done be introducing pointers to functions B and C, called pA and pB, and
calling A with a pointer argument p that is evaluated either as the pointer of
B or as the pointer of C – that is, p=pB or p=pC.


If the prototype of a function is:

double functionname(double, double);

its pointer is declared as:


double (*othername)(double, double) = functionname;

The function may then be called as


c = functionname(a, b);

or


c = (*othername)(a, b);

For example, consider the following code consisting of three functions and
the main program, contained in the filepointerfun.cc:


#include <iostream>
using namespace std;

double ratio(double, double); // function prototype
double (*pointratio)(double, double)=ratio; // and its pointer

double product(double, double); // function prototype
double (*pointproduct)(double, double)=product; // and pointer

/*--------------------------------------------------
The following is a function prototype; the arguments consist of two
"double" scalars and the pointer of a function that receives
two doubles and returns one double
-----------------------------------------------------*/

double operate(double, double, double(*)(double, double));

/*--------------- main program --------------------*/

int main()
{
Free download pdf