Why should using namespace std;
be avoided?
Reason 1: To avoid name collision.
Because the C++ standard library is large and constantly expanding, namespaces in C++ are used to lessen name collisions. You are importing everything wholesale when you use "using namespace std;".
That's why "using namespace std;" will never appear in any professional code.
Reason 2: Failed compilation.
Because it pulls the hundreds of things (classes, methods, constants, templates, etc.) defined in the std namespace into the global namespace. And it does so, not just for the file that writes “using namespace std” itself, but also for any file that includes it, recursively. This can very easily lead to accidental ODR violations and hard-to-debug compiler/linker errors.
Example:
You use the std namespace when you declare the function "max" in the global namespace.
Since you aren't using the cmath header, everything appears to be working well.
When someone else includes your file and the cmath header, their code unexpectedly fails to build because there are two functions with the name "max" in the global namespace.
Reason 3: May not work in future.
Even worse, you can't predict what changes will be made to the std:: namespace in the future. This means that code that functions today might cease to function later if a newly added symbol clashes with something in your code.
Reason 4: Difficult to maintain and debug.
The use of namespace std; can produce difficult-to-maintain and difficult-to-debug code. This is due to the fact that it is not always obvious where certain aspects come from. A developer might be referring to the std::string class or a unique string class if they use the term "string" without more explanation.
Code with namespace std
#include <iostream>
#include <algorithm>
using namespace std;
int swap = 0;
int main() {
cout << swap << endl; // ERROR: reference to "swap" is ambiguous
}
#include <iostream>
#include <algorithm>
using namespace std;
int swap = 0;
int main() {
cout << swap << endl; // ERROR: reference to "swap" is ambiguous
}
Without namespace
#include <iostream>
int main() {
using std::cout; // This only affects the current function
cout << "Hello" <<'\n';
}
#include <iostream>
int main() {
using std::cout; // This only affects the current function
cout << "Hello" <<'\n';
}
But you can use if,
you can use that if want to make short tutorials or programs, etc.
no problem using "using namespace std" in your source file when you make heavy use of the namespace and know for sure that nothing will collide.