2

The prototype of my swap function is void swap(int *a, int *b); why is it invoked when I call swap(a, b) where a and b are integers?

Full program

#include <iostream>
void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main()
{
    using namespace std;
    int a = 9, b = 8;
    cout << "before swap:" << endl;
    cout << a << '\t' << b << endl;
    swap(a, b);
    cout << "after swap:" << endl;
    cout << a << '\t' << b << endl;
    cin.get();
    return 0;
}

Observed behavior

before swap:
9    8
after swap:
8    9

I know it should have been swap(&a,&b) to call the function swap. Why does it work nonetheless?

YSC
  • 38,212
  • 9
  • 96
  • 149
Clancy Zeng
  • 159
  • 10
  • 9
    You've likely included `std::swap` via `#include `. Your swap doesn't look like it's ever used. Another example of `using namespace std;` leading to subtle errors. – François Andrieux Jan 03 '19 at 15:08
  • 5
    Because you have `using namespace std`. You have `std::swap`, not your swap. Bad practice to use this command. – Matthieu Brucher Jan 03 '19 at 15:08
  • 9
    This is [why `using namespace std` is considered bad practice](https://stackoverflow.com/q/1452721/5470596). – YSC Jan 03 '19 at 15:09
  • I think there are lots of similar questions on SO with exactly the same `swap`. – Matthieu Brucher Jan 03 '19 at 15:09
  • It didn’t use your swap function – Killzone Kid Jan 03 '19 at 15:10
  • @YSC I have heard this in the univercity, but without examples, and I'm not working with C, and now I actually know why it is a bad practice. I have upvoted the question for your comment :) – Nikita Jan 03 '19 at 15:12
  • 2
    This is not a bad question per se. You provided us with a [mcve], explained the observed behavior and why it surprises you. This is just a classic error we've seen many times. Don't be sorry. – YSC Jan 03 '19 at 15:21
  • I am sorry ! I have got it .Thank you ! – Clancy Zeng Jan 03 '19 at 15:27
  • Most of the times, when the users ask or search for something like this, they don't have any idea of what "using namespace std" means. Actually, the way this question is, it can be more useful than the one linked as a dupe. – Victor Schröder Jan 03 '19 at 16:57

0 Answers0