|
|
 |
|
|
|
|
23: }
24: else
25: cout << Error encountered!!\n;
26: return 0;
27: }
28:
29: short Factor(int n, int *pSquared, int *pCubed)
30: {
31: short Value = 0;
32: if (n > 20)
33: Value = 1;
34: else
35: {
36: *pSquared = n*n;
37: *pCubed = n*n*n;
38: Value = 0;
39: }
40: return Value;
41: } |
|
|
|
|
|
|
|
|
Enter a number
(020): 3
number: 3
square: 9
cubed: 27 |
|
|
|
|
|
|
|
|
Analysis: On line 10, number, squared, and cubed are defined as ints. number is assigned a value based on user input. This number and the addresses of squared and cubed are passed to the function Factor(). |
|
|
|
|
|
|
|
|
Factor() examines the first parameter, which is passed by value. If it is greater than 20 (the maximum value this function can handle), it sets return Value to a simple error value. Note that the return value from Function() is reserved for either this error value or the value 0, indicating all went well; also note that the function returns this value on line 40. |
|
|
|
|
|
|
|
|
The actual values needed, the square and cube of number, are returned not by using the return mechanism, but rather by changing the pointers that were passed into the function. |
|
|
|
|
|
|
|
|
On lines 36 and 37, the pointers are assigned their return values. On line 38, return Value is assigned a success value. On line 40, return Value is returned. |
|
|
|
|
|
|
|
|
One improvement to this program might be to declare the following: |
|
|
|
|
|
|
|
|
enum ERROR_VALUE { SUCCESS, FAILURE}; |
|
|
|
|
|
|
|
|
Then, rather than returning 0 or 1, the program could return SUCCESS or FAILURE. |
|
|
|
|
|