When using C++ namespaces, do you prefer to explicitly name them, like this:
std::cout << "Hello, world!\n";
Or do you prefer using namespace
:
using namespace std;
cout << "Hello, world!\n";
And if if you prefer the latter, do you declare your usings at file or function scope?
Personally I prefer to explicitly name them - it's more typing but when using a mixture of namespaces (e.g. std
and boost
) I find it more readable.
The biggest advantage of using namespace is that the class names which are declared in one namespace will not clash with the same class names declared in another namespace. It is also referred as named group of classes having common features.
The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.
using namespace std; are used. It is because computer needs to know the code for the cout, cin functionalities and it needs to know which namespace they are defined.
A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
I use always explicit ones. Writing std does not hurt me and I clearly see where is it from. It's useful when you have some legacy project to take care of with it's own "strings", "vectors" etc to maintain. The more information the code carries with it, the better.
Extra typing is not the issue here. The problem with explicitly qualified names is the visual clutter. Let's face it, C++ syntax is untidy. No need to make this worse by needlessly making names longer and sprinkling the code generously with ::
s.
I'm with Jeff Atwood: The Best Code is No Code At All. This is so true.
Namespace imports are a great way of reducing clutter with no drawback: As long as the scope of opened namespaces is reduced to a single compilation unit1, name conflicts, should they appear, can be resolved easily.
Why explicit names should (in general) be more readable has always been a mystery to me. The readers should generally know the code good enough to be able to deduce semantics. If they aren't, the code needs fixing anyway.
1) Corollary: no using
in headers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With