|
|
|
|
|
|
|
LISTING 11.5 PASSING BY REFERENCE USING POINTERS |
|
|
|
 |
|
|
|
|
1: //Listing 11.5 Demonstrates passing by reference
2:
3: #include <iostream.h>
4:
5: void swap(int *x, int *y);
6:
7: int main()
8: {
9: int x = 5, y = 10;
10:
11: cout << Main. Before swap, x: << x << y: << y << \n;
12: swap(&x,&y);
13: cout << Main. After swap, x: << x << y: << y << \n;
14: return 0;
15: }
16:
17: void swap (int *px, int *py)
18: {
19: int temp;
20:
21: cout << Swap. Before swap, *px: << *px << *py:
<< *py << \n;
22:
23: temp = *px;
24: *px = *py;
25: *py = temp;
26:
27: cout << Swap. After swap, *px: << *px << *py:
<< *py << \n;
28:
29: } |
|
|
|
|
|
|
|
|
Main. Before swap. x: 5 y: 10
Swap. Before swap. *px: 5 *py: 10
Swap. After swap. *px: 10 *py: 5
Main. After swap. x: 10 y: 5 |
|
|
|
|
|
|
|
|
Analysis: Success! On line 5, the prototype of swap() is changed to indicate that its two parameters will be pointers to int rather than int variables. When swap() is called on line 12, the addresses of x and y are passed as the arguments. |
|
|
|
|
|
|
|
|
On line 19, a local variable, temp, is declared in the swap() function. Temp need not be a pointer; it will just hold the value of *px (that is, the value of x in the calling function) for the life of the function. After the function returns, temp will no longer be needed. |
|
|
|
|
|