Exploiting References 271
9
18: cin >> number;
19:
20: result = Factor(number, squared, cubed);
21:
22: if (result == SUCCESS)
23: {
24: cout << “number: “ << number << endl;
25: cout << “square: “ << squared << endl;
26: cout << “cubed: “ << cubed << endl;
27: }
28: else
29: cout << “Error encountered!!” << endl;
30: return 0;
31: }
32:
33: ERR_CODE Factor(int n, int &rSquared, int &rCubed)
34: {
35: if (n > 20)
36: return ERROR; // simple error code
37: else
38: {
39: rSquared = n*n;
40: rCubed = n*n*n;
41: return SUCCESS;
42: }
43: }
Enter a number (0 - 20): 3
number: 3
square: 9
cubed: 27
Listing 9.9 is identical to 9.8, with two exceptions. The ERR_CODEenumeration
makes the error reporting a bit more explicit on lines 36 and 41, as well as the
error handling on line 22.
The larger change, however, is that Factor()is now declared to take references to
squaredand cubedrather than to pointers. This makes the manipulation of these parame-
ters far simpler and easier to understand.
Passing by Reference for Efficiency....................................................................
Each time you pass an object into a function by value, a copy of the object is made. Each
time you return an object from a function by value, another copy is made.
OUTPUT
LISTING9.9 continued
ANALYSIS