This question may be a duplicate, but I can\'t find a good answer. Short and simple, what requires me to declare
using namespace std;
in C+
The ability to refer to members in the std
namespace without the need to refer to std::member
explicitly. For example:
#include <iostream>
using namespace std;
...
cout << "Hi" << endl;
vs.
#include <iostream>
...
std::cout << "Hi" << std::endl;
It's used whenever you're using something that is declared within a namespace. The C++ standard library is declared within the namespace std. Therefore you have to do
using namespace std;
unless you want to specify the namespace when calling functions within another namespace, like so:
std::cout << "cout is declared within the namespace std";
You can read more about it at http://www.cplusplus.com/doc/tutorial/namespaces/.
All the files in the C++ standard library declare all of its entities within the std namespace.
e.g: To use cin,cout
defined in iostream
Alternatives:
using std::cout;
using std::endl;
cout << "Hello" << endl;
std::cout << "Hello" << std::endl;
Since the C++ standard has been accepted, practically all of the standard library is inside the std namespace. So if you don't want to qualify all standard library calls with std::
, you need to add the using directive.
However,
using namespace std;
is considered a bad practice because you are practically importing the whole standard namespace, thus opening up a lot of possibilities for name clashes. It is better to import only the stuff you are actually using in your code, like
using std::string;
Nothing requires you to do -- unless you are implementer of C++ Standard Library and you want to avoid code duplication when declaring header files in both "new" and "old" style:
// cstdio
namespace std
{
// ...
int printf(const char* ...);
// ...
}
.
// stdio.h
#include <cstdio>
using namespace std;
Well, of course example is somewhat contrived (you could equally well use plain <stdio.h>
and put it all in std in <cstdio>
), but Bjarne Stroustrup shows this example in his The C++ Programming Language.
You should definitely not say:
using namespace std;
in your C++ headers, because that beats the whole point of using namespaces (doing that would constitute "namespace pollution"). Some useful resources on this topic are the following:
1) stackoverflow thread on Standard convention for using “std”
2) an article by Herb Sutter on Migrating to Namespaces
3) FAQ 27.5 from Marshall Cline's C++ Faq lite.