1

Can anyone explain the logic behind the working of defined function in this program. This gives the correct output in this case even after commenting the whole logic of function.

#include <iostream>
using namespace std;
void swap(int *a, int *b)
{ /*
int temp=0;
 temp= *a;
 *a= *b;
 *b=temp;
*/
}
int main()
{
    int x, y;
    cout << "This program is the demo of function call by pointer \n\n";
    cout << "Enter the value of x & y \n";
    cout << "x: ";
    cin >> x;
    cout << "y: ";
    cin >> y;
    cout << "Value befor swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    swap(x, y);
    cout << "Value after swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    return 0;
}
Blaze
  • 16,736
  • 2
  • 25
  • 44

3 Answers3

11

That's why you shouldn't do using namespace std;, it just leads to confusion like this.

What happens is that std::swap is called instead when you do swap(x, y);.

By the way, your swap won't work. It takes int pointers, but you give it int. This wouldn't compile, you need to do swap(&x, &y); instead. It only worked because it was always using std::swap.

Blaze
  • 16,736
  • 2
  • 25
  • 44
5

swap is ambiguous between your definition and std::swap. If you want to keep the using namespace std you need to encapsulate your method declaration in a class or a namespace and call YourNamespaceOrClass::swap(a, b) explicitely

cfaz
  • 185
  • 7
  • 1
    Nitpick: The problem isn't that the `swap` call is ambiguous - if it was OP would get a compiler error pointing at the offending call. The problem is that `std::swap` is an unambiguously better match for the call, which leads to OP's confusion. But I will concede that this is arguing semantics. :) – Frodyne Feb 18 '20 at 08:46
  • 1
    @Frodyne Nitpick: OP's `std::swap` isn't even only a *better match*. OP's `swap` is not a viable overload for the call at all. ;) – walnut Feb 18 '20 at 17:44
  • I didn't thought about it but yes, the std::swap isn't using pointers but references, that is why the call is working – cfaz Feb 18 '20 at 17:48
2

Declaring using namespace std; means that you are using all the functions inside the namespace std. Now, in your code you have your own version of swapfunction which is void swap(int *a, int *b).

The program worked fine in coincidence, because the namespace std has pre-defined function of swap() that accepts integers. Without this, your program will not work as your function created takes a pointer. That means, you need to pass the address of the variable swap(&var1, &var2).

This is called Function Overloading. It finds the correct function that fits based on the parameters.

Hint: Avoid using using namespace std; as it will have problem(collisions) in bigger projects if you're not keen to your created functions.

Master James
  • 318
  • 5
  • 18