Figure 8.6 and Fig. 8.7 present two versions of a function that cubes an integer. Figure 8.6 passes variable number
by value (line 14) to function cubeByValue
(lines 19–22), which cubes its argument and passes the new value back to main
using a return
statement (line 21). The new value is assigned to number
(line 14) in main
. The calling function has the opportunity to examine the function call’s result before modifying variable number
’s value. For example, we could have stored the result of cubeByValue
in another variable, examined its value and assigned the result to number
only after determining that the returned value was reasonable.
1 // Fig. 8.6: fig08_06.cpp
2 // Pass-by-value used to cube a variable's value.
3 #include <iostream>
4 using namespace std;
5
6 int cubeByValue( int ); // prototype
7
8 int main()
9 {
10 int number = 5;
11
12 cout << "The original value of number is " << number;
13
14 number = cubeByValue( number ); // pass number by value to cubeByValue
15 cout << "
The new value of number is " << number << endl;
16 } // end main
17
18 // calculate and return cube of integer argument
19 int cubeByValue( int n )
20 {
21 return n * n * n; // cube local variable n and return result
22 } // end function cubeByValue
The original value of number is 5
The new value of number is 125
1 // Fig. 8.7: fig08_07.cpp
2 // Pass-by-reference with a pointer argument used to cube a
3 // variable's value.
4 #include <iostream>
5 using namespace std;
6
7 void cubeByReference( int * ); // prototype
8
9 int main()
10 {
11 int number = 5;
12
13 cout << "The original value of number is " << number;
14
15 cubeByReference( &number ); // pass number address to cubeByReference
16
17 cout << "
The new value of number is " << number << endl;
18 } // end main
19
20 // calculate cube of *nPtr; modifies variable number in main
21 void cubeByReference( int *nPtr )
22 {
23 *nPtr = *nPtr * *nPtr * *nPtr; // cube *nPtr
24 } // end function cubeByReference
The original value of number is 5
The new value of number is 125