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 does it risk declaring ambiguous variables (variables that share the same name as a function in std
namespace)? Does it impact performance?
This is not related to performance at all. But consider this: you are using two libraries called Foo and Bar:
Everything works fine, you can call
Blah()
from Foo andQuux()
from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function calledQuux()
. Now you've got a conflict: Both Foo 2.0 and Bar importQuux()
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()
andbar::Quux()
, then the introduction offoo::Quux()
would have been a non-event.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.
I recently ran into a complaint about Visual Studio 2010. It turned out that pretty much all the source files had these two lines:
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.Another reason is surprise.
If I see
cout << blah
, instead ofstd::cout << blah
I think what is this
cout
? Is it the normalcout
? Is it something special?From my experiences, if you have multiple libraries that uses say,
cout
, but for a different purpose you may use the wrongcout
.For example, if I type in,
using namespace std;
andusing namespace otherlib;
and type just cout (which happens to be in both), rather thanstd::cout
(or'otherlib::cout'
), you might use the wrong one, and get errors, it's much more effective and efficient to usestd::cout
.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:
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).