|
|
 |
|
|
|
|
14: return 0;
15: }
16:
17: void swap (int x, int y)
18: {
19: int temp;
20:
21: cout << Swap. Before swap, x: << x << y: << y << \n;
22:
23: temp = x;
24: x = y;
25: y = temp;
26:
27: cout << Swap. After swap, x: << x << y: << y << \n;
28:
29: } |
|
|
|
|
|
|
|
|
Main. Before swap. x: 5 y: 10
Swap. Before swap. x: 5 y: 10
Swap. After swap. x: 10 y: 5
Main. After swap. x: 5 y: 10 |
|
|
|
|
|
|
|
|
Analysis: This program initializes two variables in main() and then passes them to the swap() function, which appears to swap them. But when they are examined again in main(), they are unchanged! |
|
|
|
|
|
|
|
|
The problem here is that x and y are being passed to swap() by value. That is, local copies were made in the function. What you want is to pass x and y by reference. |
|
|
|
|
|
|
|
|
There are two ways to solve this problem 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 using pointers, the function, swap(), should be declared to accept two int pointers. Then, by dereferencing the pointers, the values of x and y will, in fact, be swapped. Listing 11.5 demonstrates this idea. |
|
|
|
|
|