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++ programs?
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++ programs?
Nothing does, it's a shorthand to avoid prefixing everything in that namespace with std::
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:
.
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.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,
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
You never have to declare using namespace std; using it is is bad practice and you should use std:: if you don't want to type std:: always you could do something like this in some cases:
By using std:: you can also tell which part of your program uses the standard library and which doesn't. Which is even more important that there might be conflicts with other functions which get included.
Rgds Layne
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
unless you want to specify the namespace when calling functions within another namespace, like so:
You can read more about it at http://www.cplusplus.com/doc/tutorial/namespaces/.
The ability to refer to members in the
std
namespace without the need to refer tostd::member
explicitly. For example:vs.