std:: or using namespace std

Why so many people use std:: instead of just writing using namespace std at the top?
Prefixes objectively add clarity to the code & personal preference.
There are many variables and function names in the std libs. All of these names are generally kept simple to make them easy to use. Unfortunately this also means that other libs that I might want to include might have the same variable/function names. This leads to ambiguity over which function is actually being called, especially if a using namespace is called in a header file.

I would argue that in a small program that you're making for your own use, this is not such a big issue. This is more of a production-code issue; In general it's pretty simple to avoid these name-clashes by getting just a little bit clever with your name choices in your own code. It gets exponentially more difficult as new coders join the crew, different company libraries are used, and all this code and libraries are updated over time. (Just look at how many libraries have been added to C++ in the last 20 years with C++20 libs on the way)

Last edited on
Depends on the user design.

Namespaces prevents larger variables from overwriting one another in larger projects.

Which is why they created using namespace in replace of typedefs or possibly enhance the declarations.

Last edited on
1. Names which potentially collide result in programs which don't port;
2. Argument-dependent lookup is prone to extremely subtle bugs and further portability issues; and
3. If all names are qualified, an unqualified name communicates a desire to rely on ADL.
Last edited on
There are a lot of names in the std:: namespace. If put using namespace std in your code, then suddenly they are all visible. So what happens if you innocently happen to use one of those names (like log or list)?

If you're lucky, the compiler will give you a very strange and cryptic message that makes zero sense because you're focused on your definition of the name and aren't even considering the library's definition.

If you're unlucky, the program will compile without warning and will do something completely different from what you intended.

And don't forget that they add new names to the std:: with each new standard, so you your code is fine with C++17 but conflicts with C++20.

I prefer to add "using" for each std symbol that I'm actually using. For a small file, you can probably have using namespace std without much danger. But then again, why be lazy.

Never put using namespace std in a header file. People who include your header file aren't expecting it to pull hundreds (thousands?) of names.
Topic archived. No new replies allowed.