function rather than where it belongs—on the function being called. Listing 9.7 rewrites
the swap()function, using references.
LISTING9.7 swap()Rewritten with References
1: //Listing 9.7 Demonstrates passing by reference
2: // using references!
3: #include <iostream>
4:
5: using namespace std;
6: void swap(int &x, int &y);
7:
8: int main()
9: {
10: int x = 5, y = 10;
11:
12: cout << “Main. Before swap, x: “ << x << “ y: “
13: << y << endl;
14:
15: swap(x,y);
16:
17: cout << “Main. After swap, x: “ << x << “ y: “
18: << y << endl;
19:
20: return 0;
21: }
22:
23: void swap (int &rx, int &ry)
24: {
25: int temp;
26:
27: cout << “Swap. Before swap, rx: “ << rx << “ ry: “
28: << ry << endl;
29:
30: temp = rx;
31: rx = ry;
32: ry = temp;
33:
34:
35: cout << “Swap. After swap, rx: “ << rx << “ ry: “
36: << ry << endl;
37:
38: }
Main. Before swap, x:5 y: 10
Swap. Before swap, rx:5 ry:10
Swap. After swap, rx:10 ry:5
Main. After swap, x:10, y:5
OUTPUT
266 Day 9