How this c++ code runs without definition of function

我只是一个虾纸丫 提交于 2020-05-23 11:15:24

问题


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

回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/60276091/how-this-c-code-runs-without-definition-of-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!