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.