I was messing with a function that swaps the value of two variables using pointer and I found out that by declaring using namespace std
, I wouldn't need to pass the address of the variables as arguments for it to work. Passing the int itself would make the code works.
I suspect it has something to do with how std process arguments but I couldn't find an answer for it. I'd appreciate it if someone could point me to the right direction.
1) Without using namespace std
#include<iostream>
void swap(int* X, int* Y);
int main() {
int a, b;
std::cin >> a;
std::cin >> b;
std::cout << a << "," << b << std::endl;
swap(&a, &b);
std::cout << a << "," << b << std::endl;
}
void swap(int* X, int* Y) {
int temp = *X;
*X = *Y;
*Y = temp;
}
2) With using namespace std
#include<iostream>
**using namespace std;**
void swap(int* X, int* Y);
int main() {
int a, b;
std::cin >> a;
std::cin >> b;
std::cout << a << "," << b << std::endl;
swap(a, b);
std::cout << a << "," << b << std::endl;
}
void swap(int* X, int* Y) {
int temp = *X;
*X = *Y;
*Y = temp;
}
It doesn't. With using namespace std;
you wind up calling std::swap which takes its parameters by reference. This is one of the many reasons that using namespace std
is very bad practice.