I've been told by others that writing using namespace std in code is wrong, and that I should use std::cout and std::cin directly instead.

Why is using namespace std considered a bad practice? Is it inefficient or risk declaring ambiguous variables (variables that share the same name as a function in std namespace)? Does it impact performance?

331 upvote
  flag
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
upvote
  flag
@a paid nerd google-styleguide.googlecode.com/svn/trunk/… link does not work anymore. Looks like new link is google.github.io/styleguide/cppguide.html#Other_C++_Features – MCG
12 upvote
  flag
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. – sh-
upvote
  flag
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. – Ludovic Zenohate Lagouardette

34 Answers 11

Another reason 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 something special?

up vote 1532 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 had used foo::Blah() and bar::Quux(), then the introduction of foo::Quux() would have been a non-event.

274 upvote
  flag
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
546 upvote
  flag
@Pax namespace io = boost::filesystem; – AraK
106 upvote
  flag
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
211 upvote
  flag
Would any sensible person create a library with types whose unqualified name collide with the std types? – erikkallen
7 upvote
  flag
@MattyT: Things can get much worse than "having to fix". (see my answer: //allinonescript.com/questions/1452721/1453605#1453605). – sbi
57 upvote
  flag
@erikkallen: That the std lib has taken hundreds (or even thousands) of names, many of which are very popular and common (error, list, sort), was, IIRC, an important reason for putting it into its own namespace. – sbi
1 upvote
  flag
To replicate the python "import longlongnamespace as spc" behaviour you can simply use a #define. I don't see anything wrong with that. – Tomas Andrle
68 upvote
  flag
@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
42 upvote
  flag
For the record, a namespace alias is using namespace bhn = big_honkin_name; as opposed to #defines or a using statement within a new namespace. – AshleysBrain
13 upvote
  flag
Why is this more of a problem in C++ than it is in C#? As far as I can see C# has exactly the same potential problem, but nobody would ever dream of using (for example) Company.Product.Component.Foo instead of just Foo – Justin
3 upvote
  flag
@Kragen: C++'s namespaces are large, while C#'s a relatively granular. (For the record I prefer at least partially qualified names in C# too but that's a whole different topic...) – Billy ONeal
13 upvote
  flag
@erikkallen Maybe not, but suppose you want to port your C++03 program to C++11 and find out std added a few things. – Lee Louviere
12 upvote
  flag
@erikkallen Of course you would, considering that it contains such nice and common names like vector, set, or transform and that noone should blindly use using namespace std, anyway. Of course naming your things my_complex_vector_type or perform_a_transformation or set_this_value out of mere fear of std names is rubbish and completely invalidates the purpose of namespaces anyway. – Christian Rau
2 upvote
  flag
@AraK A little too ignorant here... What do you mean by boost::filesystem? Does using the io namesapce improve performance? Sorry if this sounds silly :) – itsols
2 upvote
  flag
@itsols. AraK is talking about namespace alias: link – JACH
12 upvote
  flag
@erikkallen Boost, a well known C++ library, has many things that collide with iostream. – Kevin Chen
upvote
  flag
So, as long as you use only one using namespace and it's not in the header file, you should be fine?? – Shayan RC
2 upvote
  flag
@ShayanRC Unfortunately there are libraries that don't use namespaces, so even one using namespace can create problems. Of course if you use multiple libraries that don't use namespaces then you're S.O.L. – bames53
4 upvote
  flag
@erikkallen What if someone wrote a class called unordered_map back in 2000, before it was in the standard library? – immibis
2 upvote
  flag
So...using a namespace alias has been agreed to be the best way to avoid writing the entire namespace? Also, @bill commented about using namespace std::cout and using namespace std::cin -- did anyone see any potential issue with this, or is it deemed safe? It seems to me like this would avoid the "conflicting namespaces" issue while still allowing me to write cout << some code or cin >> some code, and only reserving std:: calls to the lesser-used std namespace calls. – Alex G
4 upvote
  flag
But why would someone ever create a function which is called "cout" or "cin"`!? I think this is all nonsense, i will keep using namespace std; forever because i don't think that someone will create a function called "cout","cin" or other well known functions like these. – Black
9 upvote
  flag
@EdwardBlack cout and cin may not be the best examples, but some names are much more common and can be used by various libraries to mean different things. For example, there is a std::vector, a boost::mpl::vector, a boost::numeric::ublas::vector, which are all very different but all deserve the name vector. – Luc Touraille
3 upvote
  flag
@EdwardBlack Other examples of common names used in the std are system, time, pair, map, min, merge... Are you saying that no one should ever use these names in their libraries? – Luc Touraille
upvote
  flag
why would someone use "system" or "time"? – Black
4 upvote
  flag
@EdwardBlack: say you get some long protocol document from a stock exchange, in which "system" identifies something about the exchange; if you don't use the same identifier, you complicate adoption of and comparison against pseudo-code in the document, use of the document's index to find related info, the common terminology with which you can talk to people at the exchange about data issues etc.. Of course, the same issue exists for keywords, but that's no reason not to match exactly when you can. – Tony Delroy
1 upvote
  flag
@MattyT I think you're right, assuming you're the only programmer on the project and you're aware of the conflict when you upgrade to Foo 2.0. – thohl
3 upvote
  flag
-1: This answer explains a potential clean-up task that may be necessary in the future, but not why it's a bad idea. Ending up with namespace conflicts happens in other languages, too, and as long as the compiler gives you a clear heads-up, it's usually not a big deal. – Slipp D. Thompson
1 upvote
  flag
Using qualified name of a function prevents ADL. So there could not be a definite "never use using" rule. – grisumbras
2 upvote
  flag
@SlippD.Thompson: This answer really outlines the best that can happen: The compiler no longer compiling your code. No harm done. Another answer by sbi adds, that a far worse scenario is, if the compiler continues to compile your code. But with changed semantics. It silently compiles code you never intended to write. Now that is bad. – IInspectable
1 upvote
  flag
@IInspectable I added more info regarding this to a comment on sdi's answer. Historically, this was a problem. However, modern compilers emit warnings or errors in this situation. That is, no, the compiler doesn't silently compile, it very specifically errors “reference to 'string' is ambiguous”. – Slipp D. Thompson
5 upvote
  flag
Seems like a defensive practice against a very rare case that is easily fixed. Among all the things that cause bugs, std namespace collisions must rank very low. Defensive practices have a cost. It's not a no-brainer. – usr
1 upvote
  flag
@itsols The point is to do less typing, and making the code more readable. – DBedrenko
upvote
  flag
I wouldn't consider that to be a problem at all as you get compilation error and you can fix it. Real problem may happen when compiler starts to silently use wrong function. For example, if you used bar::Quux(unsigned int) and then foo::Quux(int) was added. – Pavel
upvote
  flag
I downvoted this answer because I am highly unconvinced that libraries actually name their functions the same as the ones from std. I will also keep using it. There is no effort to fix, only a rename would ever be necessary. – Zimano
5 upvote
  flag
Highly unconvinced? Oh boy! You never heard of Boost, don't you? std::filesystem and boost::filesystem, std::error_code and boost::system::error_code, std::chrono, boost::chrono, std::mt19937 and boost::random::mt19937 and many many more – Ivan
upvote
  flag
@Zimano - take a longer view. How do you know that new things won't get added to std as enhancements in the future, which conflict with code or libraries that you already have? – greggo

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.

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.

Consider

// 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.

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.


Beware that some people disagree with my saying "feel free" like this -- because although a using statement in a cpp file is better than in a header (because it doesn't affect people who include your header file), they think it's still not good (because depending on the code it could make the implementation of the class more difficult to maintain). This FAQ topic says,

The using-directive exists for legacy C++ code and to ease the transition to namespaces, but you probably shouldn’t use it on a regular basis, at least not in your new C++ code.

It suggests two alternatives:

  • A using declaration:

    using std::cout; // a using-declaration lets you use cout without qualification
    cout << "Values:";
    
  • Get over it and just type std::

    std::cout << "Values:";
    
20 upvote
  flag
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
2 upvote
  flag
Have you tried this at all? Because the using namespace directive will not carry over into another file. (GCC 4.8+) – zackery.fix
3 upvote
  flag
@zackery.fix, "Apple LLVM version 7.0.2 (clang-700.1.81)" propagates using namespace std; from header to source file, and I verified that GCC does not. So at least having the "using" directive in header is risky. – Franklin Yu
upvote
  flag
Yea.. I don't use LLVM or clang and this is not a standard approach anyway. – zackery.fix
3 upvote
  flag
You really should not tell people to "feel free" with using namespace std in a .cpp file. @Étienne is right. – einpoklum
upvote
  flag
One danger, even in a "private" cpp file, is that you'll add another header to implement a new function at a later time, and it will break "stable" code elsewhere in the file. Just for one example. Don't do it. "Private" or not, header or cpp, just don't. – Jfevold
upvote
  flag
@einpoklum: But they are "free" to do so. – Lightness Races in Orbit
upvote
  flag
@LightnessRacesinOrbit: If ChrisW wrote "but you are "free" to do so" with the quotation marks this advice would not be that bad. People should certainly not feel 224-upvote free to using namespace std in their .cpp files. – einpoklum
upvote
  flag
@einpoklum Is the recent edit suitable? – ChrisW
upvote
  flag
@ChrisW: It essentially contradicts your "feel free" statement, but it's good enough for me to +1 you now. – einpoklum
upvote
  flag
@einpoklum: But, once more, they absolutely are free to do so (left out the quotation this time so you can't misrepresent my statement). It is not up to you to tell 224 people what they can and can't do... – Lightness Races in Orbit
upvote
  flag
@LightnessRacesinOrbit: You're making an epistemological argument. Are they free because it is not up to us to forbid them? Or are they not free because it has negative reprecussions which they must consider and beware? I would say option 2. Anyway, they shouldn't "feel free" even if they "are free" to do so. – einpoklum
upvote
  flag
@einpoklum: I'm not making any "argument" at all - I'm just pointing out that you cannot take away my freedom or anyone else's freedom or my ability to feel freedom to write using namespace std, whether you like it or not! You have literally no control over the matter. So why do you keep saying people shouldn't feel free to do whatever they want? It makes no sense and you should stop... – Lightness Races in Orbit
upvote
  flag
@LightnessRacesinOrbit: We're talking about an answer on SO about what people should and shouldn't do. Nobody is taking anybody's freedom to do anything. – einpoklum
upvote
  flag
I've used std in a cpp file (depending on the project), though I avoid doing so in any header file. – ChrisW
upvote
  flag
Always what i do!! This is an awesome alternate! – amanuel2

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.

6 upvote
  flag
+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
upvote
  flag
To be fair, though, you don't have most of those if you don't include <iomanip>. Still, good point. – einpoklum

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.

  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'.

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 to Quux() than the bar::Quux() your code called for years. Then your code still compiles, but it 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 Stack Overflow 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 used to writing 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 don't find std:: painful enough to employ using directives even once every 100 kLoC 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.

89 upvote
  flag
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
9 upvote
  flag
@Lie: Whether you like short or long prose is a subjective preference. (I have met developers who actually liked long identifiers, even though it meant they had to split their lines for even the simplest function calls.) Whether you see exactly which identifier, OTOH, is referred to is an objective criterion. FWIW, I used to share your POV, was forced to taste the other side, and never looked back. – sbi
10 upvote
  flag
@sbi: While I do not disagree that for non-std:: identifiers, being able to see where a name comes from can improve readability. I think the std:: denotation is just superfluous. Despite being an objective criterion, it has superficial value since you should expect any competent C++ programmer to know C++ standard libraries; and you'd expect no sane programmers would deliberately clash names with a standard library names. Personally, I put using namespace std on all of my code; though I use other namespaces conservatively, depending on frequency of usage. – Lie Ryan
61 upvote
  flag
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
6 upvote
  flag
@Lie: "I think the std:: denotation is just superfluous." Your main argument against typing out full identifiers, that they add to identifier length, will hardly apply to std::. But even so, I disagree. See this problem why. – sbi
5 upvote
  flag
@sbi: They applies much more so to std:: because they're used extremely frequently, at least in my codes. std::cout, std::cin, and std::endl is especially the most obscene offender. For vector/iterators, I'd write typedefs. Otherwise you end up with std::vector<std::string>::iterator. The problem you mentioned, is because someone named a function with the same name as a standard library function; I think you'd agree your solution with using &*ii is ridiculous, but IMO changing distance to take const& is just slightly less ridiculous. Better solution would be just to rename distance(). – Lie Ryan
9 upvote
  flag
@Lie: "The problem you mentioned, is because someone named a function with the same name as a standard library function" And that's exactly the problem! How do you propose to avoid that? In the std namespace are hundreds (if not thousands) of identifiers, among them very popular ones. There are so many, you simply can't avoid clashing with them. And that's why they are all in std. Add using namespace std to your files, and sooner or later you run into such problems. – sbi
58 upvote
  flag
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
4 upvote
  flag
@sbi, @jalf: It uglifies your code, and I'm not going to take "no" for that. – Lie Ryan
11 upvote
  flag
@sbi: Because I'm seeing someone who comes to love the bondage & discipline of having to write redundant std:: everywhere. I can't trust his rationality any longer. – Lie Ryan
1 upvote
  flag
It seems like a reasonable compromise would be to import namespace std in source files, but not import anything else. That avoids prefixing those library symbols that are likely the most frequently called, and also prevents the possibility of a namespace clash. – RjOllos
8 upvote
  flag
@RjOllos: It's spelled using in C++. That aside: Yes, you could do all kinds of compromises, but my argument was that 1) you can still run into problems (//allinonescript.com/questions/2879555/2880136#2880136), 2) code is, objectively, more readable when more explicit (because it spells out exactly what it does), and 3) it's wholly unnecessary, because abbreviating things is just a habit you can shed. Heck, there's many people writing Java, and some even write code in languages like Ada which really is a talkative language. I try to not to have to type StringUtilities::. But std::? – sbi
99 upvote
  flag
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. – Mateen Ulhaq
5 upvote
  flag
@LieRyan it's three characters. The benefit outweighs the cost like an elephant outweighs a fly. – Thoughtful Dragon
29 upvote
  flag
@LieRyan Then good luck writing a geometry library without ever naming something vector, transform or distance. And those are just examples of the many many very common names used in the standard library. Suggesting not to use them out of fear or a biased opinion of the namespace feature that is an integral part of C++ is rather counter-productive. – Christian Rau
6 upvote
  flag
“Explicitly prefixing everything doesn't do any harm” except where it breaks argument-dependent lookup (ADL) for e.g. swap. See also here. In those cases, using std::swap is better than directly calling std::swap. – MvG
6 upvote
  flag
@MvG: Of course, as with any rules, there's exceptions. That doesn't change the fact that, generally, using namesapce std; is considered a bad practice. – sbi
10 upvote
  flag
This sounds dumb: it has taken me until now to realize the significance of knowing exactly what is going on in your programs. My teacher has always said, "You don't need to know that" whenever asked a question concerning the behind-the-scenes 'stuff' - something that has always unsettled me. But, Greg's answer has completely justified my curiosity and need to know what's going on. – Thomas
9 upvote
  flag
the prefixes objectively add clarity to the code that's a substitution of opinion for an "objective" thing. By that logic, boost::numeric::ublas::vector_range<boost::numeric::ublas::v‌​ector<...>,> is the most readable and clear thing out there. Also, the example: 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. is also pretty subjective. In other words, downvote. – DarkWanderer
upvote
  flag
Sounds like compiler warnings could help identify cases when there are better matches happening for functions with same names but different namespaces originally. This would take at least part of the problem away. – alexandroid
3 upvote
  flag
@alexandroid: How do you propose compilers find out that your call used to end up with a different overload last week? Because that's a very probable scenario. – sbi
upvote
  flag
Oh no, I mean much simpler check - just the fact that some function being called has an overload from a different namespace (regardless of whether args match or not). Since we are talking about the case when both of functions are visible at the same time... (it won't help if there is a complete switch of course, i.e. one "using namespace" was replaced by another). – alexandroid
3 upvote
  flag
@alex: But ADL calls functions in other namespaces all the time! Every time you add two std::string instances, for example. Or call any other operator that's defined in a different namespace. – sbi
5 upvote
  flag
If it's really "no big deal" to write "std::" before every standard identifier, why did C++ introduce namespaces at all? They could have defined all the standard identifiers with a C-style prefix, with names such as std_string, std_cout, etc... to avoid name conflicts. The whole point of namespaces is that you can write "using" if you're going to make use of those symbols, but can still disambiguate if needed (with emphasis on if). Without using 'using', namespaces are no better than C-style identifier prefixes. – Brandin
1 upvote
  flag
@Brandin: How would you make ADL work with prefixes instead of namespaces? How would you call swap() so that any user-provided version is picked up? How would you do std::placeholders with prefixes? (You did read my answer thoroughly before criticizing, right? So you read the part where I said "except for function scopes", didn't you?) – sbi
upvote
  flag
I agree with the general statement, that using namespace std; can be harmful, but I disagree with some of your arguments: First about your datapoint: Just because developers don't use using namespace std; in function scope doesn't mean, they wouldn't use it in file scope, if it were allowed there. If your functions are short, the "price-benefit-ratio" is much worse in the function scope case. Second about readability: You wrote in a comment that "code is, objectively, more readable when more explicit". – MikeMB
2 upvote
  flag
... I don't think it's that easy: Adding std:: everywhere pushes the relevant parts more apart, makes the code broder and - in some / many cases - doesn't add any relevant information. This actually makes it more difficult to read and it depends on the situation and the reader, which effect actually is stronger. You probably also don't add unnecessary parenthesis to a sequence of math operations, although it would be more explicit. – MikeMB
upvote
  flag
upvote
  flag
Are there no compiler flags to warn/error when the same name is used in a file, and appears in multiple namespaces, regardless of specializations? This seems like something people who write compilers would account for. – Slipp D. Thompson
1 upvote
  flag
@Slipp: No, there most likely aren't, and you'd be very surprised about their results if there were any. Having programmed in C++ before namespaces were thought up, I can assure you that there's dozens of identical identifiers in every non-trivial C++ project. Clashes were a real problem back then. That is, after all, why namespaces were invented. If compilers warned about this, then we'd be right back at square one, where we can't use the same identifiers in different parts of the code. – sbi
1 upvote
  flag
@sbi That makes sense, but a compiler warning would only make sense for things that are currently clashing— identifiers in the root namespace, or in ones you're using, and only for identifiers you're actually using in a given source file (the warning would be on the usage, not the declaration) . When an unwanted clash appears, you'd know to kill one of the usings in that file and be explicit instead. Maybe the namespaces are far more bloated in C++'s libs, but beyond that I guess I don't see how this is different from namespaces in C# or Java. – Slipp D. Thompson
1 upvote
  flag
@SlippD.Thompson In short, what we need is not "same identifier error", but simply a "clash warning". I guess we should just not rely on compilers to choose. – Franklin Yu
upvote
  flag
@FranklinYu Right. I'd assume it's works like Clang's other redefinition warnings where it gives you a list of all instances it's clashing with. Especially handy if that's integrated nicely into your IDE (like Clang is with Xcode). – Slipp D. Thompson
2 upvote
  flag
@FranklinYu Turns out Clang does indeed do exactly this— it gives me a hard “reference to 'string' is ambiguous” error. Proof here: cl.ly/eruf This is using a somewhat dated version of Clang (Xcode 5.1.1's Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)), so if you're using Clang it's highly likely that you're already benefiting from this protection. | Sorry sbi, I have to downvote this one now. Historically this was a big issue, sure. But AFAIC it isn't any more. – Slipp D. Thompson
3 upvote
  flag
@SlippD.Thompson, I got another example for function clashes. We see that it does not complain on identical identifiers (or there would have been an error at line 11), not even when they are both imported into root namespace (or there would have been an error at line 18), because actually I can access both safely with explicit namespace as line 22 and 23 (although not suggested). | Hence @sbi, I don't like using namespace std; globally as well, but it would not lead to the claimed problem with a modern compiler, so sorry for my downvote. – Franklin Yu
upvote
  flag
I really like to refer to things in the narrowest posslbe scope, just like declaring variables at the site of first use, so I have no need for top level using namespace ns; but I do find using std::cout; at the function level to be rather elegant. – Aluan Haddad
upvote
  flag
I'm sure everybody gets the point, there is no need to shout. – Matti Virkkunen
upvote
  flag
Morale of the story -> don't use std at all ;-). – ColdSteel

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. ;)

5 upvote
  flag
That's a local using declaration, a very different thing from a using directive. – sbi

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).

6 upvote
  flag
I'm sorry, but I strongly disagree with this. – Billy ONeal
3 upvote
  flag
@Billy: There is no other way to support calling userlib::cos(userlib::superint). Every feature has a use. – Zan Lynx
12 upvote
  flag
@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
1 upvote
  flag
@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
upvote
  flag
@sbi: I don't see why an overload is required when a template specialization does the same job and doesn't require the caller to remember to activate ADL. (By not qualifying swap) – Billy ONeal
10 upvote
  flag
@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
24 upvote
  flag
@BillyONeal: Your (7-times-upvoted!) comment is wrong -- the situation you describe is exactly what ADL was designed to cover. Briefly, if x has one or more "associated namespaces" (e.g. if it was defined in namespace userlib) then any function call that looks like cos(x) will additionally look in those namespaces -- without any using namespace userlib; beforehand being necessary. Zan Lynx is right (and C++ name lookup is byzantine...) – j_random_hacker
2 upvote
  flag
Instead of using namespace std;, I would prefer using std::sin; using std::cos; using std::exp;. You get the same benefit without any of the risks of dumping std::* into a function. – Ferruccio

I recently ran into a complaint about Visual Studio 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 Visual Studio 2010 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.

2 upvote
  flag
This. Boost and std have a lot of overlap - especially since C++11. – einpoklum

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. A minor point is that it's not elegant to write more code when less code suffice without good reason. A major point is turning off ADL.

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

So the 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
3 upvote
  flag
Define "elegance". – sbi

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 your 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_;
public:
    // ...
    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 any more. The implementation of std::swap was changed to find a potential overload and choose it.

4 upvote
  flag
"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
upvote
  flag
@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
upvote
  flag
@ChristianRau Cant find a definitive link right now (need to go back to work), but I got to n3490 and n1252 – towi
11 upvote
  flag
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
upvote
  flag
@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
5 upvote
  flag
The final sentence is wrong. In C++11 the Std Swap Two Step was officially blessed as the right way to call swap, and various other places in the standard were changed to say they call swap like that (N.B. as stated above, using std::swap is the right way, not using namespace std). But std::swap itself was emphatically not changed to find some other swap and use it. If std::swap gets called, then std::swap gets used. – Jonathan Wakely
3 upvote
  flag
It might be wiser to just type using std::swap locally though, to reduce the local namespace while at the same time creating self-documenting code. You are rarely ever interested in the whole std namespace, so just out pick out the parts you are interested in. – Lundin

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.

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.

"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?

17 upvote
  flag
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
2 upvote
  flag
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
1 upvote
  flag
Readability. cout << hex << setw(4) << i << endl; is easier to read than std::cout << std::hex << std::setw(4) << i << std::endl; – oz1cz
12 upvote
  flag
And even worse: std::map<std::string,std::pair<std::string,std::string>> is horrible compared to map<string,pair<string,string>>. – oz1cz
2 upvote
  flag
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. – juzzlin
upvote
  flag
Agree with @juzzlin--the best code these days barely shows types at all. You can make the compiler infer almost everything with 'auto'. Only headers really have much call to specify, since the code needed to infer the type is usually not present. – Aiken Drum

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.

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).

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.

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 it is your own. So again, redefinition will not happen.

upvote
  flag
Creating collisions isn't that hard - short strings like min, end and less appear in the std:: namespace. But more, now that std:: has thousands of symbols in it, it's useful for the reader to know where a new symbol they might not know comes from. – Tom Swirly
upvote
  flag
The std namespace exists because people, either you, your colleagues, or people writing middleware you use, are not always wise about putting functions inside of namespaces. Thus you may import all of std:: and nothing else, while still invoking a collision between, say, std::min and someone else's legacy ::min() from before the time when it was in std. – Aiken Drum

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 could 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.

1 upvote
  flag
How do you know "std::cout << 1" isn't reading a static int named cout in std namespace shifting it by one and throwing away result? Also how do you know what "<<" does ;) ??? ... seems like this answer is not good data point to avoid 'using'. – nyholku
upvote
  flag
If someone has redefined std::cout to be an integer, then your problem isn't technical, but social -- someone has it in for you. (and you should probably also check all of the headers for things like #define true false, etc) – Jeremy Friesner

I agree with others - it is asking for name clashes, ambiguities and then the fact is it is less explicit. While I can see the use of using ... my personal preference is to limit it. I would also strongly consider what some others pointed out:

If you want to find a function name that might be a fairly common name, but you only want to find it in std namespace (or the reverse: you want to change all calls that are NOT in namespace std, namespace X, ...), then how do you propose to do this? You could write a program to do it but wouldn't it be better to spend time working on your project itself rather than writing a program to maintain your project?

Personally I actually don't mind the std:: prefix. I like the look more than not. I don't know if that is because it is explicit and says to me "this isn't my code... I am using the standard library" or if it is something else, but I think it looks nicer. This might be odd given that I only recently got in to C++ (used and still do C and other languages for much longer and C is my favourite language of all time, right above assembly).

There is one other thing although it is somewhat related to the above and what others point out. While this might be bad practise, I sometimes reserve std::name for standard library version and name for program-specific implementation. Yes indeed this could bite you and bite you hard but it all comes down to that I started this project from scratch and I'm the only programmer for it. Example: I overload std::string and call it string. I have helpful additions. I did it in part because of my C and Unix (+ Linux) tendency towards lower-case names.

Besides that, you can have namespace aliases. Here is an example of where it is useful that might not have been referred to (I didn't read all the responses and I'm having to rush off for a while in a moment). I use the C++11 standard and specifically with libstdc++. Well check this. It doesn't have complete std::regex support. Sure it compiles but it throws an exception along the lines of it being an error on the programmer's end. But it is lack of implementation. So here's how I solved it. Install boost's regex, link in boost's regex. Then, I do the following so that when libstdc++ has it implemented entirely, I need only remove this block and the code remains the same:

namespace std
{
    using boost::regex;
    using boost::regex_error;
    using boost::regex_replace;
    using boost::regex_search;
    using boost::regex_match;
    using boost::smatch;
    namespace regex_constants = boost::regex_constants;  
}

I won't argue on whether that is a bad idea or not. I will however argue that it keeps it clean for MY project and at the same time makes it specific: True I have to use boost BUT I'm using it like the libstdc++ will eventually have it. Yes, starting your own project and starting with a standard (...) at the very beginning goes a very long way with helping maintenance, development and everything involved with the project!

Edit: Now that I have time, just to clarify something. I don't actually think it is a good idea to use a name of a class/whatever in the STL deliberately and more specifically in place of. string is the exception (ignore the first, above, or second here, pun if you must) for me as I didn't like the idea of 'String'. As it is, I am still very biased towards C and biased against C++. Sparing details, much of what I work on fits C more (but it was a good exercise and a good way to make myself a. learn another language and b. try not be less biased against object/classes/etc which is maybe better stated as: less closed-minded, less arrogant, more accepting.). But what IS useful is what some already suggested: I do indeed use list (it is fairly generic, is it not ?), sort (same thing) to name two that would cause a name clash if I were to do "using namespace std;" and so to that end I prefer being specific, in control and knowing that if I intend it to be the standard use then I will have to specify it. Put simply: no assuming allowed.

And as for making boost's regex part of std. I do that for future integration and - again, I admit fully this is bias - I don't think it is as ugly as boost::regex:: ... Indeed that is another thing for me. There's many things in C++ that I still have yet to come to fully accept in looks and methods (another example: variadic templates versus var args [though I admit variadic templates are very very useful!]). Even those that I do accept it was difficult AND I still have issues with them.

Short version: don't use global using declarations or directives in header files. Feel free to use them in implementation files. Here's what Herb Sutter and Andrei Alexandrescu have to say about this issue in C++ Coding Standards (bolding for emphasis is mine):

Summary

Namespace usings are for your convenience, not for you to inflict on others: Never write a using declaration or a using directive before an #include directive.

Corollary: In header files, don’t write namespace-level using directives or using declarations; instead, explicitly namespace-qualify all names. (The second rule follows from the first, because headers can never know what other header #includes might appear after them.)

Discussion

In short: You can and should use namespace using declarations and directives liberally in your implementation files after #include directives and feel good about it. Despite repeated assertions to the contrary, namespace using declarations and directives are not evil and they do not defeat the purpose of namespaces. Rather, they are what make namespaces usable.

29 upvote
  flag
Sad that this sane guidance is so buried under misguided answers. – nyholku
2 upvote
  flag
Just one more programmer's opinion here, but while I agree 100% with the statement that the word using should never appear in a header, I'm not as convinced about the free license to place using namespace xyz; anywhere in your code, especially if xyz is std. I use the using std::vector; form, since that only pulls a single element from the namespace into pseudo-global scope, therefore leading to far less risk of a collision. – dgnuff
1 upvote
  flag
@Lightness Races in Orbit you are of course entitled to your opinion. Would have been more helpful if there had been some attempt at explanation why you do not agree with advice given in this answer. Especially would be interesting to understand what is the point of namespaces if 'using' them is bad? Why not just name things std_cout instead of std::cout ... the creators of C++/namespace must have had some idea when they bothered to create them. – nyholku
upvote
  flag
@nyholku: No need - the majority of the other answers give the same reasons I would. Also please do no hesitate to note the ":)" I appended to my comment! And that I didn't say namespaces are bad. – Lightness Races in Orbit
upvote
  flag
Yeah, I noticed that :) but IMO the majority of answer (that go against this sage advice) are misguided (not that I made any statistics what is the majority now). If you agree that namespace are 'not bad' then you might say where you think they are appropriate if you disagree with this answer? – nyholku

An example where using namespace std throws complilation error because of the ambiguity of count, which is also a function in algorithm library.

#include <iostream>

using namespace std;

int count = 1;
int main() {
    cout<<count<<endl;
}
1 upvote
  flag
::count--problem solved. Usually you'll have more stuff from the std namespaced than from elsewhere, ergo keeping the using namespace directive might save you typing. – PSkocik
upvote
  flag
The real problem here is that C++ still has namespace-less globals. This, and the fact that 'this' is implicit in methods, causes so many bugs and problems I can't even count them, even with the right 'count' variable. ;) – Aiken Drum

I agree with the others here, but would like to address the concerns regarding readability - you can avoid all of that by simply using typedefs at the top of your file, function or class declaration.

I usually use it in my class declaration as methods in a class tend to deal with similar data types (the members) and a typedef is an opportunity to assign a name that is meaningful in the context of the class. This actually aids readability in the definitions of the class methods.

//header
class File
{
   typedef std::vector<std::string> Lines;
   Lines ReadLines();
}

and in the implementation:

//cpp
Lines File::ReadLines()
{
    Lines lines;
    //get them...
    return lines;
}

as opposed to:

//cpp
vector<string> File::ReadLines()
{
    vector<string> lines;
    //get them...
    return lines;
}

or:

//cpp
std::vector<std::string> File::ReadLines()
{
    std::vector<std::string> lines;
    //get them...
    return lines;
}
upvote
  flag
Just a minor comment, while typedef is useful I'd consider making a class that represents Lines instead of using typedef. – Eyal Solnik

A namespace is a named scope. Namespaces are used to group related declarations and to keep separate items separate. For example, two separately developed libraries may use the same name to refer to different items, but a user can still use both:

namespace Mylib{
    template<class T> class Stack{ /* ... */ };
    / / ...
}
namespace Yourlib{
    class Stack{ /* ... */ };
    / / ...
}
void f(int max) {
    Mylib: :Stack<int> s1(max) ; / / use my stack
    Yourlib: :Stack s2(max) ; / / use your stack
    / / ...
}

Repeating a namespace name can be a distraction for both readers and writers. Consequently, it is possible to state that names from a particular namespace are available without explicit qualification. For example:

void f(int max) {
    using namespace Mylib; / / make names from Mylib accessible
    Stack<int> s1(max) ; / / use my stack
    Yourlib: :Stack s2(max) ; / / use your stack
    / / ...
}

Namespaces provide a powerful tool for the management of different libraries and of different versions of code. In particular, they offer the programmer alternatives of how explicit to make a reference to a nonlocal name.

Source : An Overview of the C++ Programming Language by Bjarne Stroustrup

3 upvote
  flag
Very interesting that a this answer that is based on guidance from no other that Bjarne Stroustrup has earned -2... boy Bjarne must have been a poor and inexperienced programmer when he introduced this feature into C++ – nyholku
upvote
  flag
@nyholku: See this. – sbi
upvote
  flag
specifically what in this? – nyholku

Here is an example showing how using namespace std; can lead to name clash problems:

Unable to define a global variable in c++

In the example a very generic algorithm name (std::count) name clashes with a very reasonable variable name (count).

From my experiences, if you have multiple libraries that uses say, cout, but for a different purpose you may use the wrong cout.

For example, if I type in, using namespace std; and using namespace otherlib; and type just cout (which happens to be in both), rather than std::cout (or 'otherlib::cout'), you might use the wrong one, and get errors, it's much more effective and efficient to use std::cout.

A concrete example to clarify the concern. Imagine you have a situation where you have 2 libraries, foo and bar, each with their own namespace:

namespace foo {
    void a(float) { /* does something */ }
}

namespace bar {
    ...
}

Now let's say you use foo and bar together in your own program as follows:

using namespace foo;
using namespace bar;

void main() {
    a(42);
}

At this point everything is fine. When you run your program it 'does something'. But later you update bar and let's say it has changed to be like:

namespace bar {
    void a(float) { /* does something completely different */ }
}

At this point you'll get a compiler error:

using namespace foo;
using namespace bar;

void main() {
    a(42);  // error: call to 'a' is ambiguous, should be foo::a(42)
}

So you'll need to do some maintenance to clarify which 'a' you meant (i.e. foo::a). That's probably undesirable, but fortunately it is pretty easy (just add foo:: in front of all calls to a that the compiler marks as ambiguous).

But imagine an alternative scenario where bar changed instead to look like this instead:

namespace bar {
    void a(int) { /* does something completely different */ }
}

At this point your call to a(42) suddenly binds to bar::a instead of foo::a and instead of doing 'something' it does 'something completely different'. No compiler warning or anything. Your program just silently starts doing something complete different than before.

When you use a namespace you're risking a scenario like this, which is why people are uncomfortable using namespaces. The more things in a namespace the greater the risk of conflict, so people might be even more uncomfortable using namespace std (due to the number of things in that namespace) than other namespaces.

Ultimately this is a trade-off between writability vs reliability/maintainability. Readability may factor in also, but I could see arguments for that going either way. Normally I would say reliability and maintainability are more important, but in this case you'll constantly pay the writability cost for an fairly rare reliability/maintainability impact. The 'best' trade-off will determine on your project and your priorities.

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.

To be honest, for me, that's like discussing about the number of spaces for intendation. Using directives in headers cause damage. But in c++ files? Maybe if you use 2 namespaces at once. But if you use one, it's more about style than real efficiency. Do you know why threads about intendation are so popular? Anyone can say something about it and sound very smart and experienced.

This is a bad practice, often known as global namespace pollution. Problems may occur when more than one namespace has the same function name with signature, then it will be ambiguous for the compiler to decide which one to call and this all can be avoided when you are specifying the namespace with your function call like std::cout . Hope this helps. :)

Not the answer you're looking for? Browse other questions tagged or ask your own question.