This program initializes two variables in main()and then passes them to the
swap()function, which appears to swap them. When they are examined again in
main(), they are unchanged!
The problem here is that xand yare being passed to swap()by value. That is, local
copies were made in the function. These local copies were changed and then thrown
away when the function returned and its local storage was deallocated. What is prefer-
able is to pass xand yby reference, which changes the source values of the variable
rather than a local copy.
Two ways to solve this problem are possible in C++: You can make the parameters of
swap()pointers to the original values, or you can pass in references to the original
values.
Making swap()Work with Pointers ..............................................................
When you pass in a pointer, you pass in the address of the object, and thus the function
can manipulate the value at that address. To make swap()change the actual values of x
and yby using pointers, the function,swap(), should be declared to accept two int
pointers. Then, by dereferencing the pointers, the values of xand ywill actually be
accessed and, in fact, be swapped. Listing 9.6 demonstrates this idea.
LISTING9.6 Passing by Reference Using Pointers
1: //Listing 9.6 Demonstrates passing by reference
2: #include <iostream>
3:
4: using namespace std;
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 << endl;
12: swap(&x,&y);
13: cout << “Main. After swap, x: “ << x << “ y: “ << y << endl;
14: return 0;
15: }
16:
17: void swap (int *px, int *py)
18: {
19: int temp;
20:
21: cout << “Swap. Before swap, *px: “ << *px <<
22: “ *py: “ << *py << endl;
264 Day 9
ANALYSIS