< Previous | Contents | Next >
After declaring and initializing myScore and yourScore, I send them to cout. As you’d expect, 150 and 1000 are displayed. Next I call badSwap().
When you specify a parameter the way you’ve seen so far (as an ordinary variable, not as a reference), you’re indicating that the argument for that parameter will be passed by value, meaning that the parameter will get a copy of the argument variable and not access to the argument variable itself. By looking at the function header of badSwap(), you can tell that a call to the function passes both arguments by value.
void badSwap(int x, int y)
194 Chapter 6 n References: Tic-Tac-Toe
This means that when I call badSwap() with the following line, copies of myScore
and yourScore are sent to the parameters, x and y.
badSwap(myScore, yourScore);
Specifically, x is assigned 150 and y is assigned 1000. As a result, nothing I do with x and y in the function badSwap() will have any effect on myScore and yourScore.
When the guts of badSwap() execute, x and y do exchange values—x becomes 1000 and y becomes 150. However, when the function ends, both x and y go out of scope and cease to exist. Control then returns to main(), where myScore and yourScore haven’t changed. Then, when I send myScore and yourScore to cout, 150 and 1000 are displayed again. Sadly, I still have the small score and you still have the large one.