>> DAVID J. MALAN: Let's write a program in which we try to swap the values of
two variables, x and y.
In advance, I've written much of this program already.
First, I declare a variable, x, and store in it the value, 1.
Then I declare variable y and store in it the value, 2.
>> Then I proceed with printf to display the values of those two variables.
Then I claim with another printf to be swapping those variables.
Then I call a function called swap.
And then I claim that the variables have been swapped.
And then I print out that what I claim are the new values of x and y.
>> Now what is this function swap?
It's not something that comes with C. Indeed, if we look at the top of my
file, you'll notice that I've declared a prototype for this function swap
specifying that it takes two ints, arbitrarily called a and b, and this
function doesn't return anything.
So presumably, it does what it says in swaps a's and b's values.
Let's now implement swap.
>> First, I'm going to declare a temporary variable and assign to it
the value in a, though I could just as easily stored in it b.
I'm then going to change the value of a to be equal to that in b.
And then lastly, I'm going to change the value of b to be what a was but is
now in temp.
>> Now I claim what I've just done is logically correct.
I've stored a in a temporary variable, changed a's value to be b's, and then
changed b's value to be what a's was.
But when I compile and run this program, I worry that's not
going what I see.
>> Make, no swap.
dot slash, no swap.
And unfortunately, according to printf, the value of x and y, even
after we claim to be swapping them, is still 1 and 2.
>> Now why is that?
Well, it turns out that in main, when we call this function swap, passing in
x and y as arguments, it's actually copies of x and y that
are passed into swap.
Namely, their values 1 and 2 are passed into swap as a and b.
And it's a and b that we're ultimately swapping in main.
>> That is, 1 becomes 2, 2 becomes 1.
But because swap has no return value and because it received copies of x
and y, it's behavior has no effect on x and y.
Indeed, a and b are scoped, so to speak, to swap, whereas x and y remain
scoped to main.
>> So we have a problem.
But how to fix it?