1
void swap(int* &x, int* &y)  //reference to pointer to int
{
    int t=*x;
    *x=*y;
    *y=t;
}
int main()
{
    int x=10, y=20;
    cout<<x<<" "<<y<<endl;
    swap(x,y);               //No compilation error showed even though the
                             //args are of type int instead of int*

    cout<<x<<" "<<y<<endl;
}

The swap function takes references to pointers to integers. But I saw that it can even take args of type int and swap them. How is it possible?

Output: 10 20
        20 10
sushruta19
  • 327
  • 3
  • 12
  • 5
    Remove `using namespace std;`! – 273K Jun 26 '21 at 06:23
  • Omg Thanks. Now its showing an error. Whats the reason behind this? – sushruta19 Jun 26 '21 at 06:26
  • 2
    [`std::swap`](https://en.cppreference.com/w/cpp/algorithm/swap) – Evg Jun 26 '21 at 06:27
  • 2
    @soubhiksen, as Evg said, when you add "using namespace std;", your code uses the std::swap() method and NOT your local swap() method. So, you don't see any error. But after you remove "using namespace std;", your code uses your local swap() method, which causes the compile error. – Job_September_2020 Jun 26 '21 at 06:40

0 Answers0