How this c++ code runs without definition of funct

2020-03-30 19:50发布

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;
}

标签: c++ std swap
3条回答
Fickle 薄情
2楼-- · 2020-03-30 20:24

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.

查看更多
霸刀☆藐视天下
3楼-- · 2020-03-30 20:28

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

查看更多
一夜七次
4楼-- · 2020-03-30 20:28

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.

查看更多
登录 后发表回答