Search code examples
c++pass-by-referencefunction-pointers

C++ Swapping Values By Reference


I came across a C++ code snippet in my exams which was quite confusing (at least for me). I tried to analyze it but there is something that I am unable to understand. The code is written below:

#include <iostream>

using namespace std;

int* doMagic(int *p, int *q)
{
    int* t = new int();
    t = p;
    p = q;
    q = t;
    return t;
}

int main()
{
    int p = 5, q = 10;
    int *t = NULL;
    t = doMagic(&p, &q);
    cout<<"p = "<<p<<endl;
    cout<<"q = "<<q<<endl;
    cout<<"t = "<<*t<<endl;
    return 0;
}

The output is:

p = 5
q = 10
t = 5

Now my question is that when the values were passed by reference to doMagic function why weren't the values swapped in it.

Help will be highly appreciated.

Thanks.


Solution

  • In this code nothing gets passed by reference.

    Some pointer values (&p, &q) get passed by value.

    Because they were passed by value, they were stored into new variables in doMagic called p and q. The new variables were then swapped. The value &p was returned and stored in main's variable t.

    Also, some memory was leaked, because an int was created with new and was never destroyed with delete.