Take the 2-minute tour ×

I've been told by others on numerous occasions that my teacher was wrong in saying that we should have using namespace std; in our programs, and that std::cout and std::cin are more proper. However, they would always be vague as to why this is a bad practice.

Why is using namespace std; considered bad? Is it really that inefficient, or risk declaring ambiguous vars(variables that share the same name as a function in std namespace) that much? Or does this impact program performance noticeably as you get into writing larger applications?

share|improve this question
The Google C++ Style Guide doesn't really answer your question but has a lot of general "why"s: google-styleguide.googlecode.com/svn/trunk/… –  a paid nerd Sep 21 '09 at 3:17
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. –  Bill Sep 21 '09 at 15:29
@Bill How would that work? << "Hello, World!";? :P –  muntoo Jul 25 '11 at 23:29
@muntoo Heh. You were joking, but just in case, he meant you could type cout instead of typing std::cout. –  Mana Jul 26 '11 at 1:06
Sounds more like a Valgrind bug, as "using namespace" has no effect of that kind... –  MFH Jul 16 '12 at 6:43
show 3 more comments

23 Answers

up vote 348 down vote accepted

This is not related to performance at all. But consider this: You are using two libraries called Foo and Bar:

using namespace foo;
using namespace bar;

Everything works fine, you can call Blah() from Foo and Quux() from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function called Quux(). Now you've got a conflict: Both Foo 2.0 and Bar import Quux() into your global namespace. This is going to take some effort to fix, especially if the function parameters happen to match.

If you have used foo::Blah() and bar::Quux() then the introduction of foo::Quux() would have been a non-event.

share|improve this answer
I've always liked Python's "import big_honkin_name as bhn" so you can then just use "bhn.something" rather than "big_honkin_name.something"- really cuts down on the typing. Does C++ have something like that? –  paxdiablo Sep 21 '09 at 3:18
@Pax namespace io = boost::filesystem; –  AraK Sep 21 '09 at 3:19
I think it's overstating things to say it's "some effort to fix". You'll have no instances of the new foo::Quux so just disambiguate all your current uses with bar::Quux. –  MattyT Sep 21 '09 at 13:44
Would any sensible person create a library with types whose unqualified name collide with the std types? –  erikkallen Sep 21 '09 at 19:14
@TomA: The problem with #define is that it doesn't restrict itself to namespaces, but tramples over the whole code base. A namespace alias is what you want. –  sbi Sep 25 '09 at 8:28
show 14 more comments

I agree with everything Greg wrote, but I'd like to add: It can even get worse than Greg said!

Library Foo 2.0 could introduce a function Quux() that is an unambiguously better match for some of your calls too Quux() than the bar::Quux() your code called for years. Then your code still compiles, but silently calls the wrong function and does god-knows-what. That's about as bad as things can get.

Keep in mind that the std namespace has tons of identifiers, many of which are very common ones (think list, sort, string, iterator etc.) which are very likely to appear in other code, too.

If you consider this unlikely: There was a question asked here on SO where pretty much exactly this happened (wrong function called due to omitted std:: prefix) about half a year after I gave this answer. Here is another, more recent example of such a question.
So this is a real problem.

Here's one more data point: Many, many years ago, I also used to find it annoying having to prefix everything from the standard library with std::. Then I worked in a project where it was decided at the start that both using directives and declarations are banned except for function scopes. Guess what? It took most of us very few weeks to get to used to write the prefix and after a few more weeks most of us even agreed that it actually made the code more readable. (There's a reason for that: Whether you like shorter or longer prose is subjective, but the prefixes objectively add clarity to the code. Not only the compiler, but you, too, find it easier to see which identifier is referred to.)

In a decade, that project grew to have several million lines of code. Since these discussions come up again and again, I once was curious how often the (allowed) function-scope using actually was used in the project. I grep'd the sources for it and only found one or two dozen places where it was used. To me this indicates that, once tried, developers didn't find std:: painful enough to employ using directives even once every 100kLoC even where it was allowed to be used.

Bottom line: Explicitly prefixing everything doesn't do any harm, takes very little getting used to, and has objective advantages. In particular, it makes the code easier to interpret by the compiler and by human readers — and that should probably be the main goal when writing code.

share|improve this answer
It does significantly harm the density of code you can pack in a single line. You end up writing your code in a very long-winded way; which reduces readability. Personally, I think shorter (but not too short) code tends to be more readable (since there is less stuff to read, and less stuff to get distracted about). –  Lie Ryan Oct 28 '10 at 15:13
Guess you missed out on the old days before C++ had a standard string class, and seemingly every library had their own. Tell you what: We'll keep writing our code with std::, and you can run our code through grep -v std:: | vim when you're browsing it. Or you can teach your editor that std:: is a keyword which is to be colored the same as the background color. Whatever works. –  Mike DeSimone Oct 28 '10 at 17:31
I don't think std:: is harmful at all. It carries very important information (namely "whatever comes after is part of the standard library", and it is still a pretty short and compact prefix. Most of the time, it's no problem at all. Sometimes, you have a few lines of code where you need to refer to specific symbols in the std namespace a lot, and then a using statement in that particular scope solves the problem nicely. But in the general case, it's not noise, it conveys valuable information in addition to removing ambiguities. –  jalf Oct 28 '10 at 18:39
@Lie: If you don't want to be persuaded by rational arguments, then why do you argue? –  sbi Oct 28 '10 at 19:21
Whenever I see std::, I know it's going to be from std:: without having to think about it. If I see string or list or map by themselves, I wonder a bit. –  muntoo Sep 14 '11 at 6:50
show 13 more comments

I think it's bad to put it in the header files of your classes: because then you would be forcing anyone who wants to use your classes (by including your header files) to also be 'using' (i.e. seeing everything in) those other namespaces.

However, you may feel free to put a using statement in your (private) *.cpp files.

share|improve this answer
This is also what I have been taught. +1 –  Default May 21 '10 at 7:43
It is less bad to put it in a .cpp file than in a header, but the problem stays the same for maintainability. It is taking the risk that two functions with the same name will clash when the code/the library you use/the C++ standard gets modified. –  Étienne May 25 '13 at 13:05
add comment

I recently ran into a complaint about VS 2010. It turned out that pretty much all the source files had these two lines:

using namespace std;
using namespace boost;

A lot of Boost features are going into the C++0x standard, and VS2010 has a lot of C++0x features, so suddenly these programs were not compiling.

Therefore, avoiding using namespace X; is a form of future-proofing, a way of making sure a change to the libraries and/or header files in use is not going to break a program.

share|improve this answer
+1 for the "this actually happened to me" answer –  Calimo Feb 21 at 14:22
add comment

If you import the right header files you suddenly have names like hex, left, plus or count in your global scope. This might be surprising if you are not aware that std:: contains these names. If you also try to use these names locally it can lead to quite some confusion.

If all the standard stuff is in its own namespace you don't have to worry about name collisions with your code or other libraries.

share|improve this answer
+1 not to mention distance. still i prefer non-qualified names whereever practically possibility, since that increases readability for me. plus, i think the fact that we usually don't qualify things in oral speech, and are willing to spend time resolving possible ambiguities, means that it has value to be able to understand what one is talking about without qualifications, and applied to source code that means it's structured in such a way that it's clear what it's all about even without qualifications. –  Cheers and hth. - Alf Dec 15 '12 at 5:49
add comment

One shouldn't use using directive at global scope, especially in headers. However there are situations where it is appropriate even in a header file:

template <typename FloatType> inline
FloatType compute_something(FloatType x)
    using namespace std; //no problem since scope is limited
    return exp(x) * (sin(x) - cos(x * 2) + sin(x * 3) - cos(x * 4));

This is better than explicit qualification (std::sin, std::cos...) because it is shorter and has the ability to work with user defined floating point types (via Argument Dependent Lookup).

share|improve this answer
I'm sorry, but I strongly disagree with this. –  Billy ONeal Dec 5 '10 at 17:15
@Billy: There is no other way to support calling userlib::cos(userlib::superint). Every feature has a use. –  Zan Lynx Jun 24 '11 at 23:42
@Zan: Of course there is. using std::cos; , using std::sin, etc. The issue though is that any well designed userlib is going to have their sin and cos inside their own namespace as well, so this really doesn't help you. (Unless there's a using namespace userlib before this template and that's just as bad as using namespace std -- and the scope there is not limited.) Furthermore, the only function like this I ever see this happen to is swap, and in such cases I would recommend just creating a template specialization of std::swap and avoiding the whole problem. –  Billy ONeal Jun 24 '11 at 23:48
@Billy: Sometimes you will have to overload swap (like when you need it for you your own container). But even then a local using declaration is much better than a using directive. –  sbi May 26 '12 at 6:38
@BillyONeal: template<typename T> void swap(MyContainer<T>&, MyContainer<T>&) (There's no function template partial specialization (FTPS), so sometimes you need to resort to overloading instead. –  sbi May 30 '12 at 14:56
show 2 more comments

Do not use it globally

It is considered "bad" only when used globally. Because

  • you clutter the namespace you are programming in.
  • readers will have difficulty seeing where a particular identifier comes from, when you use many using namespace xyz.
  • whatever is true for other readers of your source code is even more true for the most frequent reader of it: yourself. Come back in a year or two and take a look...
  • if you only talk about using namespace std you might not be aware of all the stuff you grab -- and when you add another #include or move to a new C++-revision you might get name conflicts you were not aware of

You may use it locally

Go ahead and use it locally (almost) freely. This, of course, prevents you from repetition of std:: -- and repetition is also bad.

An idiom for using it locally

In C++03 there was an idiom -- boilerplate code -- for implementing a swap function for you classes. It was suggested that you actually use a local using namespace std -- or at least using std::swap:

class Thing {
    int    value_;
    Child  child_;
    // ...
    friend void swap(Thing &a, Thing &b);
void swap(Thing &a, Thing &b) {
    using namespace std;      // make `std::swap` available
    // swap all members
    swap(a.value_, b.value_); // `std::stwap(int, int)`
    swap(a.child_, b.child_); // `swap(Child&,Child&)` or `std::swap(...)`

This does the following magic

  • the compiler will choose the std::swap for value_, i.e. void std::swap(int, int)
  • If you have an overload void swap(Child&, Child&) implemented the compiler will choose it
  • If you do not have that overload the compiler will use void std::swap(Child&,Child&) and try its best swapping these.

With C++11 there is no reason to use this pattern anymore. The implementation of std::swap was changed to find a potential overload and choose it.

share|improve this answer
"The implementation of std::swap was changed to find a potential overload and choose it." - What? Are you sure about that? Though it is true that providing a custom swap in the first place isn't that much important in C++11 anymore, since the std::swap itself is more flexible (uses move semantics). But std::swap automatically chosing your own custom swap, that is absolutely new to me (and I don't really believe it). –  Christian Rau Mar 7 '13 at 17:09
@ChristianRau I think so, yes. I read this on SO somewhere. We can always ask Howard, he should know. I am digging and digging now... –  towi Mar 8 '13 at 8:44
@ChristianRau Cant find a definitive link right now (need to go back to work), but I got to n3490 and n1252 –  towi Mar 8 '13 at 8:52
Even in the swap case, the clearer (and thankfully more common) idiom is to write using std::swap; rather than using namespace std;. The more specific idiom has fewer side effects and therefore makes the code more maintainable. –  Adrian McCarthy Feb 27 at 17:24
@AdrianMcCarthy I understood that the using std::swap idiom is usable even when having to do with non-idiomatic code. But I agree, when you have 100% control over the source, better be specific. –  towi Feb 28 at 10:19
add comment

I also consider it a bad practice. Why? Just one day I thought that function of a namespace is to divide stuff so I shouldn't spoil it with throwing everything into one global bag. However, if I often use 'cout' and 'cin', I write: using std::cout; using std::cin; in cpp file (never in header file as it propagates with #include). I think that noone sane will ever name a stream cout or cin. ;)

share|improve this answer
That's a local using declaration, a very different thing from a using directive. –  sbi May 26 '12 at 6:41
add comment
  1. you need to be able to read code written by people who have different style and best practices opinions than you.

  2. If you're only using cout, nobody gets confused. But when you have lots of namespaces flying around and you see this class and you aren't exactly sure what it does, having the namespace explicit acts as a comment of sorts. You can see at first glance, 'oh, this is a filesystem operation' or 'thats doing network stuff'.

share|improve this answer
add comment

Experienced programmers use whatever solves their problems and avoid whatever creates new problems.

Thus they avoid header-file-level using-directives for obvious reason.

And they try to avoid full qualification of names inside their source files. Minor point is that it's not elegant to write more code when less code suffice without good reason. Major point is turning off ADL.

What are these good reasons? Sometimes you explicitly want turning off ADL. Sometime you want to disambiguate.

So following are ok: 1) function-level using-directives and using-declarations inside functions' implementations; 2) source-file-level using-declarations inside source files; 3) (sometimes) source-file-level using-directives.

share|improve this answer
add comment

The only reason I can think of is surprise.

If I see cout << blah, instead of std::cout << blah

I think what is this 'cout'? Is it the normal cout? Is it somethign special?

share|improve this answer
add comment


// myHeader.h
#include <sstream>
using namespace std;

// someoneElses.cpp/h
#include "myHeader.h"

class stringstream {  // uh oh

Note that this is a simple example, if you have files with 20 includes and other imports you'll have a ton of dependencies to go through to figure out the problem. The worse thing about it is that you can get unrelated errors in other modules depending on the definitions that conflict.

It's not horrible but you'll save yourself headaches by not using it in header files or the global namespace. It's probably alright to do it in very limited scopes but I've never had a problem typing the extra 5 characters to clarify where my functions are coming from.

share|improve this answer
add comment

"Why is 'using namespace std;' considered a bad practice in C++?"

I put it the other way around: Why is typing 5 extra chars is 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" down to "vector" when "vector" is one of the problem domain's most important concepts?

share|improve this answer
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... –  Jeremy Friesner Sep 3 '13 at 3:42
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. –  DaveWalley Mar 6 at 1:54
add comment

I agree that it should not be used globally, but it's not so evil to to use locally, like in a namespace. Here's an example from "The C++ Programming Language" :

namespace My_lib {

    using namespace His_lib; // everything from His_lib
    using namespace Her_lib; // everything from Her_lib

    using His_lib::String; // resolve potential clash in favor of His_lib
    using Her_lib::Vector; // resolve potential clash in favor of Her_lib


In this example, we resolved potential name clashes and ambiguities arising from their composition.

Names explicitly declared there (including names declared by using-declarations like His_lib::String) take priority over names made accessible in another scope by a using-directive (using namespace Her_lib).

share|improve this answer
add comment

It's all about managing complexity. Using the namespace will pull things in that you don't want, and thus possibly make it harder to debug (I say possibly). Using std:: all over the place is harder to read (more text and all that).

Horses for courses - manage your complexity how you best can and feel able.

share|improve this answer
add comment

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

share|improve this answer
add comment

I do not think it is necessarily bad practice under all conditions, but you need to be careful when you use it. If you're writing a library, you probably should use the scope resolution operators with the namespace to keep your library from butting heads with other libraries. For application level code, I don't see anything wrong with it.

share|improve this answer
add comment

To answer your question I look at it this way practically: a lot of programmers (not all) invoke namespace std. Therefore one should be in the habit of NOT using things that impinge or use the same names as what is in the namespace std. That is a great deal granted, but not so much compared to the number of possible coherent words and pseudonyms that can be come up with strictly speaking.

I mean really... saying "don't rely on this being present" is just setting you up to rely on it NOT being present. You are constantly going to have issues borrowing code snippets and constantly repairing them. Just keep your user-defined and borrowed stuff in limited scope as they should be and be VERY sparing with globals (honestly globals should almost always be a last resort for purposes of "compile now, sanity later"). Truly I think it is bad advice from your teacher because using std will work for both "cout" and "std::cout" but NOT using std will only work for "std::cout". You will not always be fortunate enough to write all your own code.

NOTE: Don't focus too much on efficiency issues until you actually learn a little about how compilers work. With a little experience coding you don't have to learn that much about them before you realize how much they are able to generalize good code into something something simple. Every bit as simple as if you wrote the whole thing in C. Good code is only as complex as it needs to be.

share|improve this answer
add comment

yes, the namespace is important.Once in my project, I need to import one var declartion into my source code, but when complies, it conflict with another third-party library. At the end,i have to walk it around by some other means and make the code not clear

share|improve this answer
add comment

With unqualified imported identifiers you need external search tools like grep to find out where identifiers are declared. This makes reasoning about program correctness harder.

share|improve this answer
add comment

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

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

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

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

share|improve this answer
add comment

using many namespaces at the same time is obviously a recipe for disaster but using JUST namespace std and only namespace std is not that big of a deal in my opinion because redefinition can only occur by your own code . .. so just consider them functions as reserved names like "int" or "class" and that is it.

people should stop being so anal about it. your teacher was right all along. Just use ONE namespace that is the whole point of using namespaces the first place. you are not supposed to use more than one at the same time. unless is your own. So again, redefinition will not happen

share|improve this answer
add comment

It's nice to see code and know what it does. If I see "std::cout" I know: That's the cout stream of the std library. If I see "cout" then I don't know. It could be the cout stream of the std library. Or there code be an "int cout = 0;" ten lines higher in the same function. Or a static variable named cout in that file. It could be anything.

Now take a million line code base, which isn't particularly big, and you're searching for a bug, which means you know there is one line in this one million lines that doesn't do what it is supposed to do. "cout << 1;" could read a static int named cout, shift it to the left by one bit, and throw away the result. Looking for a bug, I'd have to check that. Can you see how I really really prefer to see "std::cout"?

It's one of these things that seem a really good idea if you are a teacher and never had to write and maintain any code for a living. I love seeing code where (1) I know what it does and (2) I'm confident that the person writing it knew what it does.

share|improve this answer
add comment

Your Answer


