The difference between my_swap_f1
and my_swap_f2
is that my_swap_f2
declares its arguments to be pointer types, while my_swap_f1
declares its arguments to be reference types. References work differently from pointers in C++, and you are attempting to use references incorrectly in my_swap_f1
.
In C++ a reference type is an immutable pointer-like handle, which points to only one instance of the referred-to type and can never be reassigned. It is treated like a value of the referenced type in most expressions, meaning that you can access the referred-to instance "directly" without dereferencing anything. Thus, if you declare a reference variable int &a
, the reference a
points to exactly one int
, and you can access that int
's value by just writing a
, such as in the assignment int temp = a
(note that temp
is just an int
, not a reference). There's no need to write &a
, and doing so will in fact take the address of the int
that a
refers to (giving you a pointer-to-int
), because the "address of" operator (&
) will be applied directly to the int
value.
This will make more sense if you write your parameter declarations with the "pointer modifier" next to the type name rather than the variable name:
//This function's parameters are two pointers
int my_swap_f2(int* a, int* b);
//This function's parameters are two references
int my_swap_f1(int& a, int& b);
Then, when implementing my_swap_f1
, you can change the int
value that a
refers to by assigning to a
directly, because a
is a "reference to int
." The correct version of your function would be:
void my_swap_f1(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
Note that in line 3, the assignment overwrites the int
that a
refers to with the value of the int
that b
refers to. The references themselves cannot be changed, so there is no need to add any extra symbols (like &
) to indicate the referred-to value rather than the reference itself. (Also, I changed the function return type to void
, since your code does not actually return a value from the function, and it doesn't need to).