nebi nebi -4 years ago 108
C++ Question

Interesting case of swap with help of pointers

I was trying to generate error in swap code in C++. Interestingly, instead of error, it succesfully shows the opposite. My code look like this:

using namespace std;

void swap(int *x, int *y)
int *tmp = x;
x = y;
y = tmp;

int main()
int u = 10;
int v = 20;
int * p = &u;
int * q = &v;
swap(*p, *q);
std::cout<<"u :-"<<u<<" v :-"<<v<<endl;
return 0;

The value of
got swapped. In this, I am passing pointer value instead of reference but the value gets swapped, How?

Exact code can be found at:

Answer Source
swap(*p, *q);

Since the type of *p and *q are not int *, (it's just int) this code doesn't call your swap function. Instead, it calls the function std::swap, which is in standard C++ library, by function overloading resolving.

Your code has using namespace std; - your case is one of examples that show why you shouldn`t use it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download