C++ – Swap Function with Pointers Only Works with ‘using namespace std’

c++pointersreference

I have a bunch of code like this:

#include <iostream>
using namespace std;

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int a = 7;
    int b = 5;
    swap(a, b);
    cout << a << b; // prints 57 as expected
}

However, if I remove using namespace std, the compiler raises an error about int to int* conversion. Why does the code work with using namespace std even though I didn't use the method with the & operator?

Best Answer

In the first example, std::swap is called, because of your using namespace std. The second example is exactly the same as the first one, so you might have no using.

Anyway, if you rename your function to my_swap or something like that (and change every occurence), then the first code shouldn't work, as expected. Or, remove the using namespace std and call std::cin and std::cout explicitly. I would recommend the second option.

Related Question