3

Possible Duplicate:
Using std Namespace
Why is 'using namespace std;' considered a bad practice in C++?

Let's say I'm using #include <iostream> in C++ and I'm making a print statement. I can choose either to:

using namespace std;
[...]
cout << "Hello" << endl;

or

using std::cout;
using std::endl;
[...]
cout << "Hello" << endl;

or

std::cout << "Hello" << std::endl;

I'm led to believe, and perhaps this is incorrect, that the first one is somewhat to be avoided, as it can add a lot of unnecessary bloat to your program. However, I don't know if there's any difference between the second and third styles in terms of performance. The majority of code that I see that uses libraries tends to use the third style; however for me if there's no tradeoff in using the second one, it seems like the cleanest and most readable method, especially if you're making a lot of calls to the functions or objects in question.

Can anyone enlighten me?

Community
  • 1
  • 1
limp_chimp
  • 13,475
  • 17
  • 66
  • 105
  • 12
    `using namespace xxx;` can *never* introduce "bloat" (damn overused word). The problems lie [with possible ambiguities](http://stackoverflow.com/q/1452721/500104). "in terms of performance" -- err... The using directive / declarations only change how you *name* things, they don't change any runtime behaviour (except maybe calling the wrong function, see above). – Xeo Aug 07 '12 at 11:53
  • 2
    I prefer the third style, as it always makes clear where a specific method/type/whatever comes from. I - personally - still like it although it introduces longer "expressions". – Jakob S. Aug 07 '12 at 11:56
  • 4
    It's only five extra letters. Type it out, and thank god you're not writing Java. – Kerrek SB Aug 07 '12 at 12:00
  • When the namespaces prefixes tend to become really long, you can use a fourth alternative: [namespace aliases](http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcreating_a_namespace_alias.htm). For instance, I often do `namespace mpl = boost::mpl` (I know for sure that I don't have any other namespace named `mpl` in my project). – Luc Touraille Aug 07 '12 at 12:28

4 Answers4

11

There is no performance difference, or "bloat", whichever way you choose.

However, if you do, for example

using namespace std;
using namespace boost;

you will get in a lot of trouble with conflicting names in the two namespaces.

I think version 3, using std::cout etc everywhere, is easier to read and saves you from future name conflicts.

If that's not what you want, option 2 is the second best as it only introduces a few select names from the namespace. Note though that in your example, there is a net loss in typing because the using declarations contain more characters than you save from not typing std:: in the rest of the code.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • 1
    wouldn't agree stuffing your code full of "std::" is "easier to read"... – nonchip Aug 07 '12 at 12:10
  • @nonchip: Read the question I linked in my comment on the question. You'll certainly agree that typing `std::` instead of having to worry about nameclashes isn't that bad of a trade-off. – Xeo Aug 07 '12 at 12:13
  • 1
    No, some people disagree. However, **I** think it is easier to read (once you get used to it), because you don't have to wonder where names come from. And it is not like you have to type `std::` on every single line, do you? – Bo Persson Aug 07 '12 at 12:13
  • @Xeo sure, but only if there are any collisions. – nonchip Aug 07 '12 at 12:16
  • @Xeo: he is not saying whether it is a good or bad trade-off, only that the doesn't find that a good point for method #3. I agree with that, though I can see why other people (such as Bo) don't. – Gorpik Aug 07 '12 at 12:18
  • 1
    @nonchip - We have already seen people having problems when the new C++11 additions to namespace std collide with names from 3rd party libraries. Even if you don't have collisions right now, you might get later! – Bo Persson Aug 07 '12 at 12:18
  • 1
    @nonchip: I do quite a bit of metaprogramming with Boost.MPL and Boost.Fusion; if I see `vector` in some code, I don't know if it's an `std::vector`, a `boost::mpl::vector` or a `boost::fusion::vector`. With the prefix, no problem. – Luc Touraille Aug 07 '12 at 12:32
8

My rule of thumb: never put using namespace in a .h, but feel free to use it in a .cpp file. Especially when it's using namespace std!

Andrea Bergia
  • 5,502
  • 1
  • 23
  • 38
  • 3
    I agree. You should never put `using` statements in header files, since you are forcing them into any other file that includes them. This may well be the reason why OP doesn't see them in other files he's examined: if they belong to third party libraries, chances are they are headers. As for .cpp files, just strive for clarity, as long as you avoid name clashes. It is very unlikely that anyone will reuse names from the `std` namespace, so once again I agree. – Gorpik Aug 07 '12 at 12:02
  • 2
    @Gorpik " It is very unlikely that anyone will reuse names from the std", you should see how many SO questions boil down to re-using `std` names and getting clashes. To avoid re-using them, you need to know they are part of the namespace in the first place. I would never use `using namespace std` anywhere. – juanchopanza Aug 07 '12 at 12:05
  • @Gorpik This is a great comment! Let me just emphasize that because @Andrea Bergia didn't really mention it in his answer: **any** `using` statement in a header file is bad. Not just `using namespace`. – Alex Aug 07 '12 at 12:09
  • @juanchopanza: I was thinking about commercial library writers, but you may very well be right about other people code. – Gorpik Aug 07 '12 at 12:10
  • 1
    Frankly, someone who reuses identifiers from the `std` namespace is not a competent C++ programmer. The standard library *is* part of the language. – Andrea Bergia Aug 07 '12 at 12:14
  • 1
    @AndreaBergia: Unfortunately, non-competent programmers are a reality and we must be prepared to deal with them. – Gorpik Aug 07 '12 at 12:20
  • 1
    Note that an ambiguous name caused by `using namespace std` can be resolved by explicitly typing out `std::` or `your_namespace::` before the name, assuming your project has its own namespace. – Vortico Aug 07 '12 at 12:21
  • Unfortunately we live in a far from ideal world, where incompetent or inexperienced programmers (many of whom will become competent one day) have to work together with more competent ones, who find debugging these types of name clashes rather tedious. – juanchopanza Aug 07 '12 at 12:23
  • 5
    @AndreaBergia: That's BS, sorry. Why should I be forbidden using names like `sort`, `thread`, `find`, or something that I can't yet imagine because it is part of C++1x? Should boost now deprecate half of his library because of name clashes like `std::shared_ptr` and `boost::shared_ptr`? The whole point of namespaces is to _enable_ name reuse, so that we can rid off naming conventions like `mysql_connect()` or `andreabergia_link_open()` ... Using _clean_ names is competence, using _generic_ names is competence. Forbidding name reuse is just ignorant, because the set of names will ever evolve. – Sebastian Mach Aug 07 '12 at 13:15
4

The code produced by each of these should be exactly the same. There won't be any bloat from the first, as it merely makes all the names from std available to the code upon compilation - what isn't used isn't taken. The only names from std that were actually used were cout and endl so the end result in the compiled code is the same.

The advantages and disadvantages are:

  1. This one will have more concise code in most of the lines. Someone reading it may have to think a bit harder about where cout and endl are defined, though that's not really a big worry with something as well-known as they are. It could take a bit longer to compile, because there's a slightly larger range of possible meanings to each name, but that's probably negligible unless the program is massive and the machine you are compiling on is pretty weak. If some other namespace that's in scope defines an cout or an endl then the name will be ambiguous, and you'll be forced to use one of the others.

  2. The advantages of number 1, with the disadvantages reduced by only bringing in two names.

  3. The opposite of number one. No ambiguity for either compiler nor a developer in looking at the source, but at the cost of being more verbose.

As such, it might be worth going with approach 3 if these are the only uses of std in the whole file, number one if there's lots of stuff from std used repeatedly, and 2 if you use cout and endl a lot, but nothing else from std.

Or you can just use number 1 all the time unless forced by an ambiguity to do otherwise.

The two aren't mutually exclusive. One can do:

using namespace std;
/*...*/
std::cout << "Hello" << std::endl;

Here of course the std:: is redundant, but we might do this either if these were ambiguous in the context, but other uses of std weren't, or if people were likely to be unfamiliar with a particular name and so the redundant code helps readability. There are also some names that are just more commonly found given their full names in this manner, and doing what is common is itself an aid to readability.

Still, barring the case of ambiguity (which won't compile) all of these produce the same program upon compilation.

Edit:

I was assuming a .cpp file here, but I agree with the others about headers. In a .h file you're forcing the decision upon all the files it's included into, and it takes just one to have an ambiguity to make that a bad call. It's also less visible to a developer because the place of inclusion isn't near to the place of use.

If you really want to use 1 or 2 in a .h file, then scope the using by placing it inside a namespace, class, or function, so there aren't any surprises awaiting those who include the file.

Jon Hanna
  • 110,372
  • 10
  • 146
  • 251
  • +1 for a very complete answer, though I understand why some other people will not agree with your take on method #1. – Gorpik Aug 07 '12 at 12:13
  • @Gorpik in what way? (Though until I saw some others mention it, I didn't even consider that someone might do so in a header file, if that's what you mean). – Jon Hanna Aug 07 '12 at 13:07
  • No, I meant that some people fully oppose method #1, even for .cpp files. – Gorpik Aug 08 '12 at 09:49
  • @Gorpik Ah, that's fair enough. They can't say it doesn't have the advantage of concision, because it plainly does, they just don't think it's worth it, which doesn't contradict what I've said. I was more worried that I was missing something entirely. – Jon Hanna Aug 08 '12 at 10:42
3

I would generally prefere the third style, but sometimes it's much more compact and simple to use first or second styles. I use them locally sometimes. For example:

void foo()
{
    using namespace std;
    //do stuff
}

But I prefere not to write using namespace std globally in the module

Andrew
  • 24,218
  • 13
  • 61
  • 90