< previous page page_335 next page >

Page 335
LISTING 20.6 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
63:    void Swap(int & rX, int & rY)
64:    {
65:       int temp;
66:       temp = rX;
67:       rX = rY;
68:       rY = temp;
69:    }
70:
71:    void GetVals (int & rValOne, int & rValTwo)
72:    {
73:       cout << New value for ValOne: ;
74:       cin >> rValOne;
75:       cout << New value for ValTwo: ;
76:       cin >> rValTwo;
77:    }

Output:
(1)Change Values (2)Square (3)Cube (4)Swap: 1
(1)Change Values (2)Square (3)Cube (4)Swap: 2
(1)Change Values (2)Square (3)Cube (4)Swap: 3
(1)Change Values (2)Square (3)Cube (4)Swap: 4
(1)Change Values (2)Square (3)Cube (4)Swap: 2
New Value for ValOne: 2
New Value for ValTwo: 3
3 x: 2 y: 3
x: 4 y: 9
x: 64 y: 729
x: 729 y: 64
x: 531441 y:4096
Analysis: On lines 1830, the user is asked to pick the functions to invoke, and each member of the array is assigned the address of the appropriate function. On lines 3236, each function is invoked in turn. The result is printed after each invocation.
Passing Pointers to Functions to Other Functions
The pointers to functions (and arrays of pointers to functions, for that matter) can be passed to other functions that may take action and then call the right function using the pointer.
For example, you might improve Listing 20.6 by passing the chosen function pointer to another function (outside of main()) that will print the values, invoke the function, and then print the values again. Listing 20.7 illustrates this variation.

 
< previous page page_335 next page >

If you like this book, buy it!