0

I was actually thinking that this program should throw a Compilation Error(coz, I am passing values to swap method and not &a, &b) but I was shocked to see that it got executed Successfully. So, am posting this to know how/why it got executed without any error.

#include <iostream> 
using namespace std; 

void swap(int* x, int* y) 
{ 
    int z = *x; 
    *x = *y; 
    *y = z; 
} 

int main() 
{ 
    int a = 45, b = 35; 
    cout << "Before Swap\n"; 
    cout << "a = " << a << " b = " << b << "\n";  
    swap(a, b); 

    cout << "After Swap with pass by pointer\n"; 
    cout << "a = " << a << " b = " << b << "\n"; 
} 
Jayanth G
  • 69
  • 1
  • 4
  • 2
    `swap(&a, &b);` note that you are using `using namespace std;` and there is `std::swap`. – Marek R Jan 12 '21 at 17:03
  • 3
    Because you're calling `std::swap` instead of your own. – tkausl Jan 12 '21 at 17:05
  • https://stackoverflow.com/q/1452721/1387438 – Marek R Jan 12 '21 at 17:06
  • Thank you for the comments. I am just trying to know if I am getting it right, so what's happening is, when I call swap(a,b) and since I have not defined a swap function that receives values. Therefore it is searching for the function in the STD and because it found one there, it is getting executed, correct? – Jayanth G Jan 12 '21 at 17:24

1 Answers1

4

As is said so often on this site, using namespace std; is a bad idea.

You called std::swap<int>

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • Hey, thank you for your time. – Jayanth G Jan 12 '21 at 17:12
  • I am just trying to know if I am getting it right, so what's happening is, when I call swap(a,b) and since I have not defined a swap function that receives values. Therefore it is searching for the function in the STD and because it found one there, it is getting executed, correct? – Jayanth G Jan 12 '21 at 17:15
  • 1
    It doesn't search in `std`. You took all of the contents of `std` and put everything in the global namespace, the same namespace where you defined your own `std::swap`. Searches will look at surrounding namespaces, but not inside nested namespaces. – MSalters Jan 12 '21 at 17:25
  • I see, thanks a lot for clearing my doubts. – Jayanth G Jan 13 '21 at 12:17