A doubt in swap using pointers

#include <iostream>
using namespace std;

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?
However, how is swap(*p, *q) giving correct output?

The generic function std::swap() from the C++ standard library is being called instead of your own function.

This is a decent example of the issues that arise because of overuse of using directives such as using namespace std.

Last edited on
Thanks. Got it
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?
Last edited on
Topic archived. No new replies allowed.