25

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;
    int b;
    a = 7;
    b = 5;
    swap(a, b);
    cout << a << b;

    return 0;
}

This code does the swapping process as what I exactly wanted to swap 2 numbers, but when I want two numbers from the user as follows;

int a;
int b;
cin >> a;
cin >> b;
swap(a, b);
cout << a << b;

the compiler gives me an error about int to int* error which is as expected. Why does the first code do the right swapping although I didn't use the method with & operator?

Yun
  • 3,056
  • 6
  • 9
  • 28
w1LL1ng
  • 357
  • 1
  • 4
  • 7
  • 33
    Relevant: [Why is `using namespace std;` considered a bad practice in C++?](http://stackoverflow.com/a/1453605/140719) – sbi Nov 15 '12 at 18:54
  • The second snippet does not cause compile error with my g++-5.5 and clang++-11.0.0 – ChrisZZ Jan 27 '21 at 01:29

1 Answers1

71

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.

ipc
  • 8,045
  • 29
  • 33