#include<iostream>
usingnamespace std;
void swap(int*, int*);
void swap(int* a, int* b){
int* tmp{nullptr};
tmp = a;
a = b;
b = tmp;
}
int main()
{
int num1{23};
int num2{99};
cout << num1 << " " << num2 << "\n";
swap(num1, num2);//<==THE ARGUMENTS ARE NOT POINTERS BUT NO COMPILER ERROR EVEN WE DEFINED THE FUNCTION ARGUMENTS AS TWO POINTERS.
cout << num1 << " " << num2 << "\n";
return 0;
}
Why does not work the first code?
Why no errors in the second code and works fine?
#include<iostream>
//using namespace std;
void swap(int* a, int* b) {
int* tmp {nullptr};
tmp = a;
a = b;
b = tmp;
}
int main()
{
int num1 {23};
int num2 {99};
std::cout << num1 << " " << num2 << "\n";
swap(num1, num2);
std::cout << num1 << " " << num2 << "\n";
return 0;
}
You get a compiler error "void swap(int *,int *)': cannot convert argument 1 from 'int' to 'int *'"
The reason it worked before is that there is a swap() as part of STL and with the using statement, the STL one was used instead of the one in the code. That's why it compiled OK and ran. Removing the using statement meant that the compiler no longer considered the STL swap() as it's not in the global namespace.
This is the reason that having using... in a program is a Bad Idea.