3385

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
  • 731
    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, 2009 at 15:29
  • 123
    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-
    Jun 25, 2017 at 14:37
  • 15
    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. Jul 19, 2017 at 9:33
  • 23
    @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.
    – sh-
    Apr 9, 2018 at 14:10
  • 3
    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!
    – Brett Hale
    Aug 7, 2021 at 13:34

41 Answers 41

2855

Consider two libraries called Foo and Bar:

using namespace foo;
using namespace bar;

Everything works fine, and 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.

12
  • 595
    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, 2009 at 3:18
  • 937
    @Pax namespace io = boost::filesystem; Sep 21, 2009 at 3:19
  • 182
    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, 2009 at 13:44
  • 350
    Would any sensible person create a library with types whose unqualified name collide with the std types?
    – erikkallen
    Sep 21, 2009 at 19:14
  • 133
    @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
    Sep 22, 2009 at 12:42
1724

It can get worse than what Greg wrote!

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.

6
  • 1
    Disagree about interpretation by reader as foo::bar() can mean function bar from namespace foo or a static function from class foo.
    – convert
    Feb 9, 2022 at 21:15
  • 7
    @convert And why would anyone call a class foo instead of Foo? And static methods should also be called Foo::Bar and not Foo::bar. That's why people thought conventions are a good thing. Feb 14, 2022 at 11:20
  • 1
    @Stefan Riedel Don´t know but it´s comon practice in C++. For example it´s string and vector and not String and Vector.
    – convert
    Feb 14, 2022 at 11:41
  • 6
    @convert it's common practice in the standard lib. Most (all I know of) C++ coding conventions recommend capitalized classes. More than half the conventions I know recommend capitalized static methods. And even if you have some voodoo coding convention that does neither, having foo::bar as a static method is still no argument against the interpretation point. It's still clearer where that function/method belongs to and if you give your class a good name it's still clear that a class is meant and not a namespace. Feb 14, 2022 at 13:04
  • 1
    @convert Yes that's exactly what i'm saying. My opinion might be of little value to you, but that's even Stroustrups and Sutters opinion: C++ Core Guidelines - btw. we should stop playing necromancer with this 12.5 years old answer... Feb 14, 2022 at 14:13
579
+100

The problem with putting using namespace in the header files of your classes is that it forces 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 C++ Super-FAQ entry 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.

The FAQ suggests two alternatives:

  • A using-declaration:

    using std::cout; // a using-declaration lets you use cout without qualification
    cout << "Values:";
    
  • Just typing std::

    std::cout << "Values:";
    
7
  • 9
    Of course you should never assume the state of the global cout either, lest someone has std:cout << std::hex and failed to std::restore_cout_state afterwards. But that is a whole other fatberg.
    – Móż
    Nov 2, 2019 at 9:13
  • "However, you may feel free to put a using statement in your (private) *.cpp files." And what if a future developer team decides to change the translation unit scheme, for instance via UnityBuilds? In doubt, you'll end up with horrible undefined behavior.
    – Secundi
    Dec 16, 2020 at 14:05
  • While the concerns regarding header files can be justifiable, because of the way includes can have side effects, I feel that they are not in the case of cpp files. Let us look what happens in practically every other programming language. E.g., when you code in Java you nearly always import every symbol from the packages you use - especially the standard ones. That means you almost never expect a competing and conflicting implementation of String, List, Map, etc. The same happens for other languages that I know. It is reasonable IMO and we should make life easy not hard. Dec 21, 2020 at 15:51
  • If a team migrates to unity build, it will have to remove using keywords and cry because using stdlib without using is a pain. However, if you depend on Qt this is ok, because Qt doesn't use namespace (bless them). Still, unity builds is an edge case.
    – Kiruahxh
    Mar 10, 2021 at 16:18
  • 3
    …to you. To the vast majority of the C++ ecosystem on the other hand, including the C++ committee, common wisdom of experienced C++ developers and the creator of C++ language himself, not only that is an option, but it is also the recommended one.
    – spectras
    Apr 9, 2021 at 11:22
276

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.

4
  • 33
    This. Boost and std have a lot of overlap - especially since C++11.
    – einpoklum
    Feb 24, 2016 at 16:40
  • 2
    I did that once and learned a lesson the hard way. Now I never use using outside of a function definition and rarely use using namespace at all.
    – Ferruccio
    Apr 10, 2018 at 13:45
  • I personaly would never use boost, as it´s the worst C++ API I ever seen. Which problems I could still have then if using namespace std?
    – convert
    Feb 9, 2022 at 21:21
  • @convert Any library could in theory clash with std now or in the future. As mentioned in other answers std contains many common names like list and error. Boost just highlights the issue as it is affected now. Invoking using undoes what namespaces were supposed to fix. Be careful with it. Mar 17, 2022 at 15:53
240

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.

5
  • 15
    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
    Feb 23, 2016 at 23:51
  • 6
    I can't help but feel that using namespace is evil like goto is evil. Both have valid uses, but 999 times out of 1000 they will be used wrong. So, yeah, with using namespace in the source you won't pollute the namespace of other includes, neat. But it still won't protect you against the "fun" that arises from using namespace Foo + using namespace Bar with you calling (implicit Foo::) baz(xyz) and suddenly the code breaking (without related changes) just because because Bar::baz() got added somewhere, which just happens to be a better match (and thus now gets called instead)
    – CharonX
    Jan 9, 2020 at 8:58
  • 1
    @CharonX But won't the code only break if your source file (which calls Foo::baz()) actually #includes the header where Bar::baz() is declared? Seems not that likely to happen. It's like if I write using namespace std; in my main.cpp file, but don't #include <iostream>, then I can still define a fn in main.cpp called cout and there will be no collision. Sep 29, 2020 at 12:11
  • 4
    @AdmiralAdama Yes, of course that header needs to be included - but this can be done indirectly (headers include other headers etc.). So this bug is of the rarer kind... but when it strikes it can be very nasty (the function you call changes), very hard to detect (trigged by adding a function somewhere, so the risk of it making into release is high) and horrible to track down (the code "looks" 100% correct). I gave a more detailed example in an answer over at software engineering
    – CharonX
    Oct 8, 2020 at 7:23
  • @AdmiralAdama: That's wrong, system header files are allowed to include other system headers, so even if you did not #include <iostream>, std::cout may be in scope and if you write using namespace std; now your code runs on some platforms and breaks on others, depending on the details of whether one system header includes another (note it's sufficient for a header to #include <iosfwd>, a header which exists pretty much for the sole purpose of inclusion from other headers)
    – Ben Voigt
    Apr 1, 2022 at 16:30
144

One shouldn't use the using directive at the 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 (ADL)).

8
  • 4
    @Billy: There is no other way to support calling userlib::cos(userlib::superint). Every feature has a use.
    – Zan Lynx
    Jun 24, 2011 at 23:42
  • 20
    @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. Jun 24, 2011 at 23:48
  • 13
    @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, 2012 at 14:56
  • 43
    @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...) Sep 4, 2015 at 15:31
  • 5
    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
    May 10, 2016 at 22:18
114

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.

7
  • 7
    "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). Mar 7, 2013 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, 2013 at 8:44
  • 19
    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. Feb 27, 2014 at 17:24
  • 16
    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. Jul 16, 2015 at 10:59
  • 6
    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
    Oct 26, 2015 at 11:02
88

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.

5
  • 15
    +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. Dec 15, 2012 at 5:49
  • To be fair, though, you don't have most of those if you don't include <iomanip>. Still, good point.
    – einpoklum
    Feb 24, 2016 at 16:42
  • 1
    @einpoklum You usually don't have to include <iomanip> to get those. Including <iostream> is sufficient for all those in GCC for ex gcc.godbolt.org/z/Kqx9q1 Jul 29, 2020 at 10:48
  • Pretty sure you only need <iomanip> for the manipulators that take parameters, such as setw. Aug 6, 2021 at 17:08
  • my personal opinion: any name collision with std is a bug that should be fixed as soon as it is found Aug 26, 2022 at 0:21
64

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?

6
  • 44
    Is this a joke? I genuinely can not tell. If not then I personally would assume it's the normal 'cout' unless you don't trust the code since otherwise that would be a BEYOND MAJOR code smell, IMO. ... And if you don't trust the code then why are you using it in the first place? Note that I'm not saying "TRUST EvERYThING!!" but this also seems a bit far fetched if you're, say, dealing with some well known library from GitHub or something. Mar 5, 2018 at 22:43
  • 55
    @BrentRittenhouse cout is a bad example because everyone recognizes it. But imagine future in a financial app. Is it a contract to buy or sell something at a specified date? No it isn't. If the code said std::future you would not be so easily confused. Apr 5, 2018 at 20:20
  • 2
    @BrentRittenhouse maybe a little bad example, there are at least four different libraries that have cout. May be "is it standard library? libstdc++? stl? something else?" And no, not everyone knows std::cout, at least inherently, 6 of 7 new workers we receive don't. Because curricula of education doesn't use those in education. I have to chase away printfs. Or debugs() - from Qt. Apr 24, 2018 at 18:49
  • 3
    Really? It's pretty much in the first example of the first chapter of sooo many books on C++, if anything it (with insertion operator usage) is the only C++ some new bods know.
    – mckenzm
    Jul 29, 2019 at 5:07
  • @mckenzm I might put it in a book or lecture notes to reduce clutter, but not in code Jul 30, 2019 at 22:48
54

I agree that it should not be used globally, but it's not so evil 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).

1
  • interesting how most other answers forget to define the scope of namespace by just using curly brackets {..}
    – Ol Sen
    Apr 23, 2021 at 17:21
53

Experienced programmers use whatever solves their problems and avoid whatever creates new problems, and they avoid header-file-level using-directives for this exact reason.

Experienced programmers also try to avoid full qualification of names inside their source files. A minor reason for this is that it's not elegant to write more code when less code is sufficient unless there are good reasons. A major reason for this is turning off argument-dependent lookup (ADL).

What are these good reasons? Sometimes programmers explicitly want to turn off ADL, other times they 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
0
36

I also consider it a bad practice. Why? Just one day I thought that the 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 the .cpp file (never in the header file as it propagates with #include). I think that no one sane will ever name a stream cout or cin. ;)

1
  • 8
    That's a local using declaration, a very different thing from a using directive.
    – sbi
    May 26, 2012 at 6:41
35

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.

3
  • 7
    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
    Jun 11, 2015 at 12:43
  • 6
    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) Jul 7, 2016 at 4:33
  • 6
    When I see cout I know it's std::cout, always. If I'm wrong, it's problem of person who wrote this code, not me :)
    – Tien Do
    Aug 31, 2018 at 4:52
28

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.

3
  • "Using the namespace will pull things in that you don't want, and thus possibly make it harder to debug (I say possibly)." Using the namespace doesn't "pull in" anything. Debugging is unaffected. Feb 23, 2021 at 2:33
  • It depends upon how you define pull things in. In the context above, using it meant that everything in the std:: namespace was considered to be with the scope. Any identifier could come from that namespace, so you have to consider that when reading code. It creates an ambiguity that simply doesn't exist if you refer to something with namespace only where needed. Anything that reduced cognitive load for the reader (eg. the vast majority of the life of the code) is a good thing and conversely anything that increases it is a bad thing. Hence my disclaimer at the end. Feb 24, 2021 at 7:42
  • Using "pull things in" in this context gives the wrong impression - it gives the impression that additional namespace'd declarations will be included in the program, regardless of how you meant it. I agree with what you've said regarding cognitive load. Feb 27, 2021 at 7:32
24

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 all right to do it in very limited scopes, but I've never had a problem typing the extra five characters to clarify where my functions are coming from.

1
  • in headers for sure, but what if using namespace std is present only in the implementation files? Nov 8, 2020 at 13:26
24

A concrete example to clarify the concern. Imagine you have a situation where you have two 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 that 'a' meant foo::a. That's 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 completely 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.

2
  • 1
    The second scenario clinches the deal for me. No namespaces again. Cannot have such subtle changes in functionality going undetected under the hood. Nov 5, 2019 at 6:01
  • A fix for that problem would be to allow namespace members to be tagged with versions, and have a means by which a using directive could specify that it should bring in members that are tagged with older version numbers, but not those that are tagged with newer ones. If at the time a programmer writes a using directive, the latest version of the library is 147, the program includes that version number in the using directive, and any functions that get added later get tagged with higher numbers, the code which specifies version 147 would continue to work the same way as it always had.
    – supercat
    Apr 5, 2021 at 17:27
20
  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 "that's doing network stuff".

19

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.

2
  • 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
    May 24, 2016 at 23:32
  • 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
    Aug 23, 2017 at 14:22
14

I agree with the others here, but I 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;
}
1
  • Just a minor comment, while typedef is useful I'd consider making a class that represents Lines instead of using typedef.
    – iam3yal
    Mar 11, 2016 at 9:23
14

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

2
  • 5
    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
    Jun 11, 2015 at 12:48
  • @nyholku: See this.
    – sbi
    Aug 4, 2015 at 16:01
13

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

#include <iostream>
#include <algorithm>

using namespace std;

int count = 1;
int main() {
    cout << count << endl;
}
2
  • 3
    ::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. Jul 11, 2015 at 19:12
  • 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
    Aug 23, 2017 at 14:27
11

It's case by case. We want to minimize the "total cost of ownership" of the software over its lifespan. Stating "using namespace std" has some costs, but not using it also has a cost in legibility.

People correctly point out that when using it, when the standard library introduces new symbols and definitions, your code ceases to compile, and you may be forced to rename variables. And yet this is probably good long-term, since future maintainers will be momentarily confused or distracted if you're using a keyword for some surprising purpose.

You don't want to have a template called vector, say, which isn't the vector known by everyone else. And the number of new definitions thus introduced in the C++ library is small enough it may simply not come up. There is a cost to having to do this kind of change, but the cost is not high and is offset by the clarity gained by not using std symbol names for other purposes.

Given the number of classes, variables, and functions, stating std:: on every one might fluff up your code by 50% and make it harder to get your head around. An algorithm or step in a method that could be taken in on one screenful of code now requires scrolling back and forth to follow. This is a real cost. Arguably it may not be a high cost, but people who deny it even exists are inexperienced, dogmatic, or simply wrong.

I'd offer the following rules:

  1. std is different from all other libraries. It is the one library everyone basically needs to know, and in my view is best thought of as part of the language. Generally speaking there is an excellent case for using namespace std even if there isn't for other libraries.

  2. Never force the decision onto the author of a compilation unit (a .cpp file) by putting this using in a header. Always defer the decision to the compilation unit author. Even in a project that has decided to use using namespace std everywhere may fine a few modules that are best handled as exceptions to that rule.

  3. Even though the namespace feature lets you have many modules with symbols defined the same, it's going to be confusing to do so. Keep the names different to the extent possible. Even if not using the namespace feature, if you have a class named foo and std introduces a class named foo, it's probably better long-run to rename your class anyway.

  4. An alternative to using namespaces is to manually namespace symbols by prefixing them. I have two libraries I've used for decades, both starting as C libraries, actually, where every symbol is prefixed with "AK" or "SCWin". Generally speaking, this is like avoiding the "using" construct, but you don't write the twin colons. AK::foo() is instead AKFoo(). It makes code 5-10% denser and less verbose, and the only downside is that you'll be in big trouble if you have to use two such libraries that have the same prefixing. Note the X Window libraries are excellent in this regard, except they forgot to do so with a few #defines: TRUE and FALSE should have been XTRUE and XFALSE, and this set up a namespace clash with Sybase or Oracle that likewise used TRUE and FALSE with different values! (ASCII 0 and 1 in the case of the database!) One special advantage of this is that it applies seemlessly to preprocessor definitions, whereas the C++ using/namespace system doesn't handle them. A nice benefit of this is that it gives an organic slope from being part of a project to eventually being a library. In a large application of mine, all window classes are prefixed Win, all signal-processing modules Mod, and so on. There's little chance of any of these being reused so there's no practical benefit to making each group into a library, but it makes obvious in a few seconds how the project breaks into sub-projects.

0
10

It doesn't make your software or project performance worse. The inclusion of the namespace at the beginning of your source code isn't bad. The inclusion of the using namespace std instruction varies according to your needs and the way you are developing the software or project.

The namespace std contains the C++ standard functions and variables. This namespace is useful when you often would use the C++ standard functions.

As is mentioned in this page:

The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.

And see this opinion:

There is no problem using "using namespace std" in your source file when you make heavy use of the namespace and know for sure that nothing will collide.

Some people had said that is a bad practice to include the using namespace std in your source files because you're invoking from that namespace all the functions and variables. When you would like to define a new function with the same name as another function contained in the namespace std you would overload the function and it could produce problems due to compile or execute. It will not compile or executing as you expect.

As is mentioned in this page:

Although the statement saves us from typing std:: whenever we wish to access a class or type defined in the std namespace, it imports the entirety of the std namespace into the current namespace of the program. Let us take a few examples to understand why this might not be such a good thing

...

Now at a later stage of development, we wish to use another version of cout that is custom implemented in some library called “foo” (for example)

...

Notice how there is an ambiguity, to which library does cout point to? The compiler may detect this and not compile the program. In the worst case, the program may still compile but call the wrong function, since we never specified to which namespace the identifier belonged.

8

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 the 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 having it. 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 into 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 the 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 use the C++11 standard and specifically with libstdc++. Well, 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, and link it in. 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!

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. The 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, and more accepting.). But what is useful is what some already suggested: I do indeed use list (it is fairly generic, is it not ?), and 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 are many things in C++ that I still have yet to come to fully accept in looks and methods (another example: variadic templates versus var arguments [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.

1
8

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.

7

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.

7

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.

7

This is 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.

7

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
  • 25
    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... Sep 3, 2013 at 3:42
  • 5
    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, 2014 at 1:54
  • 1
    Readability. cout << hex << setw(4) << i << endl; is easier to read than std::cout << std::hex << std::setw(4) << i << std::endl;
    – oz1cz
    Oct 24, 2014 at 9:47
  • 18
    And even worse: std::map<std::string,std::pair<std::string,std::string>> is horrible compared to map<string,pair<string,string>>.
    – oz1cz
    Oct 24, 2014 at 10:41
  • 4
    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
    Jan 19, 2016 at 12:04
6

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.

1
  • 2
    Given how many folk seem unaware of useful standard library functions (reinventing things from <algorithm>, for example), it seems a bit of a stretch to imagine that the same people could reliably avoid those identifiers. Look through your own code and tell me you never have a variable or function called count. Or distance, or log, destroy, launch, visit, beta, sample, messages, clamp, erase, copy, modulus, left, etc. Not to mention all the identifiers not yet in std that will break your code when C++35 comes out... May 23, 2018 at 8:37

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