3458

I have heard using namespace std; is wrong, and that I should use std::cout and std::cin directly instead.

Why is this? Does it risk declaring variables that share the same name as something in the std namespace? Are there performance implications?

6
  • 752
    Don't forget you can do: "using std::cout;" which means you don't have to type std::cout, but don't bring in the entire std namespace at the same time. Commented Sep 21, 2009 at 15:29
  • 130
    It is particularly bad to use 'using namespace std' at file scope in header files. Using it in source files (*.cpp) at file scope after all includes is not quite as bad, as its effect is limited to a single translation unit. Even less problematic is using it inside functions or classes, because its effect is limited to the function or class scope. Commented Jun 25, 2017 at 14:37
  • 17
    I would discourage to use using directive but for specific namespaces like std::literals::chrono_literals, Poco::Data:Keywords,Poco::Units and stuff that will deal with literals or readability tricks. Whenever it is in header or implementation files. It might be OK in a function scope I guess, but apart from literals and stuff, it is not useful. Commented Jul 19, 2017 at 9:33
  • 25
    @Jon: It's got nothing to do with namespace std in particular. My emphasis was meant to be on "at file scope in header files". To put it as an advice: Do not use "using namespace" (std or other) at file scope in header files. It is OK to use it in implementation files. Sorry for the ambiguity. Commented Apr 9, 2018 at 14:10
  • 5
    I have no answer to add to the others, but I use: using [namespace]::[identifier]; in the local scope of relatively simple source files. For example, if I have a header frequently using the fully qualified: std::size_t type, I will typically prepend: using std::size_t; to the implementation. This simplifies reading the code, and only effects the local scope - that is: using std::[identifier]; employs the principle of least surprise. There are too many identifiers in the std namespace to keep track of. Later C++ revisions may add identifiers that clash with your own! Commented Aug 7, 2021 at 13:34

39 Answers 39

1
2
6

It depends on where it is located. If it is a common header, then you are diminishing the value of the namespace by merging it into the global namespace. Keep in mind, this could be a neat way of making module globals.

Sign up to request clarification or add additional context in comments.

Comments

6

There's a very simple answer: it's defensive programming. You know that the uses of std::size_t, std::cout, etc., could be made a little easier with using namespace std; - I hope you don't need to be convinced that such a directive has no place in a header! Within a translation unit, however, you might be tempted...

The types, classes, etc., that are part of the std namespace increase with each C++ revision. There are too many potential ambiguities if you relax the std:: qualifier. It is entirely reasonable to relax the qualifier for names within std that you will be using frequently, e.g., using std::fprintf;, or more probably, something like: using std::size_t; - but unless these are already well-understood parts of the language (or specifically, the std wrapping of the C library), just use the qualifier.

When you can use typedef, combined with auto and decltype inferencing, there's really nothing to be gained from a readability / maintainability perspective.

Comments

6

I put it the other way around: Why is typing five extra characters considered cumbersome by some?

Consider e.g. writing a piece of numerical software. Why would I even consider polluting my global namespace by cutting general std::vector<T> down to vector<T> when vector is one of the problem domain's most important concepts?

6 Comments

It's not just 5 extra chars; its 5 extra chars every time you reference any object type in the standard library. Which, if you're using the standard library very much, will be often. So it's more realistically thousands of extra chars in a decent sized program. Presumably the 'using' directive was added to the language so that it could be used...
Its not 5 extra chars every time, it is 5 chars and probably a couple mouse clicks to pull down a menu and do a Find and Replace in the editor of your choice.
Readability. cout << hex << setw(4) << i << endl; is easier to read than std::cout << std::hex << std::setw(4) << i << std::endl;
And even worse: std::map<std::string,std::pair<std::string,std::string>> is horrible compared to map<string,pair<string,string>>.
It's a good practice is to typedef your STL containers anyway so std:: there really doesn't matter. And C++11 brought us the auto keyword which makes things even easier when e.g. using iterators.
|
5
#include <iostream>

using namespace std;

int main() {
  // There used to be
  // int left, right;
  // But not anymore

  if (left != right)
    std::cout << "Excuse me, WHAT?!\n";
}

So, why? Because it brings in identifiers that overlap commonly used variable names, and lets this code compile, interpreting it to mean if (std::left != std::right).

PVS-Studio can find such an error using the V1058 diagnostic: https://godbolt.org/z/YZTwhp (thank you Andrey Karpov!!).

Pinging cppcheck developers: you might wish to flag this one. It was a doozy.

Comments

4

Yes, the namespace is important. Once in my project, I needed to import one var declaration into my source code, but when compiling it, it conflicted with another third-party library.

At the end, I had to work around around it by some other means and make the code less clear.

Comments

4

To be honest, for me, that's like discussing the number of spaces for indentation.

Using directives in headers cause damage. But in C++ files? Maybe if you use two namespaces at once. But if you use one, it's more about style than real efficiency.

Do you know why threads about indentation are so popular? Anyone can say something about it and sound very smart and experienced.

3 Comments

It only takes one example to prove a counterpoint: if (left != right) compiles with using std::namespace; without there being any left nor right in your code. It's a real bug I ran into while refactoring a real project. std is so full of common names that bugs like this are alive and well in many commercial code bases, where the original values got factored out, and the now-invalid uses remain. This was a problem in a .cpp source file, not in a header. This is not a matter of opinion. Find just one common example where silent bugs result and it's game over. Ban this stuff.
Fair point, I didn't consider that when I wrote this answer.
In cpp-Files: You might be surprised what can happen here with UnityBuilds... They are not that uncommon...
3

I think using locally or globally should depend on the application.

Because, when we use the library locally, sometimes the code is going to be a real mess. Readability is going to low.

So, we should use libraries locally only when there is a possibility for conflicts.

I am not a more experienced person. So, let me know if I am wrong.

Comments

3

Namespaces are to avoid naming conflicts. C++ is based on C and C has many problems with function and variable names because sometimes functions from different library clashes. So library developer started to prefix their functions with library names like the following:

foo/foo.h:

void libfoo_foo_foo_h_open(); // the name can be weird then even this one!

C++ introduced namespace to solve this problem in an easy way.

Assume you have two libraries named file and window which handles files and windows respectively and the following code:

#include <file.h>
#include <window.h>

using namespace file;
using namespace window;

void open() {
     ...
}

file.h:

namespace file {
    void open(); // What!
}

window.h:

namespace window {
    void open(); // Oh no!
}

The above code will surely and certainly fail to compile.

If you don't like type std:: (only 5 characters) you can always do this: (not a good idea in header files)

using s = std;

If you still want to use using namespace std; in your source file then you are inviting that problem and I have to ask you "What is the PURPOSE of a NAMESPACE?".

Comments

1

Here's a point of view I haven't found in any of the other answers: use only one namespace. The main reason why namespaces are bad, according to most of the answers, is that you can have conflicting function names which can result in a total mess. However, this won't occur if you use only one namespace. Decide which library it is that you will use the most (maybe using namespace std;) and stick with it.

One can think of it as having an invisible library prefix - std::vector becomes just vector. This, in my opinion, is the best of both worlds: on one hand it reduces the amount of typing you have to do (as intended by namespaces) and on the other, it still requires you to use the prefixes for clarity and security. If there's a function or object without a namespace prefix - you know it's from the one namespace you declared.

Just remember that if you will decide to use one globally - don't use others locally. This comes back to the other answers that local namespaces are often more useful than global ones since they provide variety in convenience.

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.