void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int main () {
int a = 100;
int b = 200;
int *p = &a;
int* q = &b;
cout<<a<<'\t'<< b << endl;
swap(*p, *q);
cout<<a<<'\t'<<b<<endl;
return 0;
}
Please see the above program of swapping 2 numbers using pointer. Ideally the function call should be made using swap(p,q) and it gives correct output. However, how is swap(*p, *q) giving correct output? What is going on inside the program that we are passing values of *p and *q and they are being received by pointer variables and giving correct output?
and, by calling std::swap, it will swap the pointers if you call it with the pointers, and that is huge.
int A = 1;
int B = 2;
int *a = &A;
int *b = &B;
swap(a,b);//swaps the pointers. to see this, set B = 3 and write out *a and *b. what is *a now?
swap(*a, *b); //swaps the data. set B =3, what is *a and *b now?
yourswap(a,b); //ok
yourswap(*a,*b); //explode. why?
can we conclude that yourswap(a,b) is misnamed and may not be doing what its name implies?