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:
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.
The advantages of number 1, with the disadvantages reduced by only bringing in two names.
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.