0

Why is the code compiling even though I am passing variables to swap function, instead of pointers or addresses?

#include <iostream>
using namespace std;
    
void swap(int *a, int *b)
{
    int *tmp;
    tmp = a;
    a = b;
    b = tmp;
}
    
int main ()
{
    int x = 1; 
    int y = 2; 
    swap (x,y); /*Note: calling swap function using actual variables, not using addresses*/
    cout << " x = " << x << "  y = " << y << endl;
}
Brian61354270
  • 8,690
  • 4
  • 21
  • 43
praful h y
  • 45
  • 4
  • 9
    hint: because of `using namespace std`. and there's why that's bad – underscore_d Aug 01 '21 at 20:20
  • 2
    I removed the `c` tag. Please only tag questions with the language that you're using. – Brian61354270 Aug 01 '21 at 20:21
  • 3
    Yet another excellent example to supplement [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/11082165). – Brian61354270 Aug 01 '21 at 20:22
  • 1
    @Brian One of the answers to that question mentions [this pretty-much exact duplicate](https://stackoverflow.com/questions/13402789/confusion-about-pointers-and-references-in-c). – interjay Aug 01 '21 at 20:26
  • @undersore_d You meant to say swap is defined already in std namespace? – praful h y Aug 01 '21 at 20:27
  • 4
    That is part of it. You may want to consider reading the link that explains why `using namespace std` is a bad practice. – drescherjm Aug 01 '21 at 20:28
  • @prafulhy Yes. `std::swap()` is a commonly used function from `namespace std`. It will be indirectly `#include`d via plenty of headers, in your case ``. `using namespace std` will pull in **everything** from `std::`, whether or not you intentionally `#include`d for it, or it was just included indirectly. As mentioned, the dupes cover all this. – underscore_d Aug 01 '21 at 20:29
  • Got it. Thank you. Should I delete the question? – praful h y Aug 01 '21 at 20:32
  • 1
    @prafulhy You should leave the question as it is. Duplicates can be helpful to direct future readers to the answer. – François Andrieux Aug 01 '21 at 20:40

0 Answers0