26

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?

2

1 Answer 1

72

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.

1
  • 42
    @w1LL1ng try removing the using namespace std. In fact, never ever use that!CommentedNov 15, 2012 at 17:26

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.