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?

Jan Schultke
43.4k8 gold badges107 silver badges188 bronze badges
asked Nov 15, 2012 at 17:17
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.

answered Nov 15, 2012 at 17:21
Sign up to request clarification or add additional context in comments.

1 Comment

@w1LL1ng try removing the using namespace std. In fact, never ever use that!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.