>> SPEAKER 1: It turns out we can successfully swap the values in two
variables by passing them into a function not by value or by copy, but
by reference or by their addresses.
In other words, we need to leverage something known as a pointer.
A pointer, really, is just the address of some variable.
And so if we provide a function called, say, swap with the address of
a variable and the address of another variable, swap should be empowered to
go to each of those addresses and actually change the
values that are there.
>> Let's see this in context.
Let's reimplement swap as follows.
First, let's change a not to be an int but to be a pointer to an int or the
address of an int.
Then let's do the same for b, changing it from an int to be a pointer to an
int or the address of an int.
>> Then inside of swap, let's still declare tmp so that we have a
temporary place for a's value.
But a's value is not a itself, because, again, a is now the address
of some int.
So if we want to go to that address and get int at that address, we have
dereference this pointer, also by way of the star operator, writing star a.
>> Next, I don't want to change the value of a.
I want to change the value at a, keeping in mind, again,
that a is an address.
So to do so, I again need to say star a gets.
And now I want to put in the value that's at b, not the value of b, which
also is an address.
>> So again I say, star b.
Then in my last line, I need to overwrite what is at address b with
what was at a's original location.
To do that, I do star b gets tmp.
>> Now at the end of the day, this function is still just
three lines of code.
But because it's manipulating values by way of their address and not the
raw values that were passed into the function, I claim that swap is now
empowered to change the values that are passed in via their addresses.
>> But I need to make one change still.
I can no longer pass in x and y themselves.
I need to pass in the addresses of x and y.
And to do that, I need some slightly different notation up top.
I want to swap x and y by passing in the address of x, indicated by
ampersand x, and the address of y, indicated by ampersand y.
>> Similarly, up top now do I need to change the function's prototype to
match the change that I've made, so that a is, again, a pointer to an int.
b is, again, a pointer to an int.
And now I can save my file.
And let's recompile and run it.
>> Make swap dot slash swap.
And this time, x and y are indeed now swapped such that their values are not
1 and 2, but 2 and 1.