I have following code,
#include <iostream>
using namespace std;
void swap(int *x, int *y)
{
int z = *x;
*x = *y;
*y = z;
}
// Driver Code
int main()
{
int a = 45, b = 35;
auto& a_ref = a;
cout << "a = " << a_ref << " b = " << b << "\n";
swap(&a_ref, &b);
cout << "After Swap with pass by pointer\n";
cout << "a = " << a << " b = " << b << "\n";
}
As can be seen, I first get a reference of a
then pass it as a pointer, I am wondering will this give undefined
sometimes?
You can't take the address of a reference. When a variable of reference type appears in an expression, it always evaluates to the object (or function) to which it refers. So the expression &a_ref
is, by all means, equivalent to &a
.
If an expression initially has the type “reference to
T
”, [...]. The expression designates the object or function denoted by the reference