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;
}
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
.
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
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 swap
function 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.