Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ does pass address of an reference as a pointer gives undefined behavior?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

[expr.type]/1:

If an expression initially has the type “reference to T”, […]. The expression designates the object or function denoted by the reference

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading