< previous page page_70 next page >

Page 70
value, which means a local copy of each argument is made in the function. These local copies are treated just as any other local variables. Listing 5.3 illustrates this point.
LISTING 5.3 DEMONSTRATES PASSING BY VALUE

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:      // Listing 5.3 - demonstrates passing by value
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 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:     }

Output:
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. When they are examined again in main(), however, they are unchanged!
The variables are initialized on line 9, and their values are displayed on line 11. swap() is called, and the variables are passed in.
Execution of the program switches to the swap() function, where on line 21 the values are printed again. They are in the same order as they were in main(), as expected. On

 
< previous page page_70 next page >

If you like this book, buy it!