views:

612

answers:

12

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?

+19  A: 

Nothing does, it's a shorthand to avoid prefixing everything in that namespace with std::

AlcariTheMad
And also regarded as poor practice.
GMan
its poor practice if you do it the global namespace :D
Hassan Syed
@GMan, @Hassan: It's perfectly fine to use it in implementation files, and dangerous in header files. Why does everyone keep saying "poor practice"? I wouldn't want to work on code where I have to type `std::` all over the place, just as I wouldn't want to import any namespace implicitly with `using namespace some_tools;`
Potatoswatter
It's poor practice because it's more likely to cause a name clash. It's better to import one symbol at a time: `using std::string` for example.
Matthieu M.
+5  A: 

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;
Alexander Gessler
+3  A: 

First of all, this is not required in C - C does not have namespaces. In C++, anything in the std namespace which includes most of the standard library. If you don't do this you have to access the members of the namespace explicitly like so:

std::cout << "I am accessing stdout" << std::endl;
Ninefingers
A: 

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;

Neeraj
+28  A: 

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;
Péter Török
+1 For being the only one to mention it's frowned upon.
GMan
A: 

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/.

Niklas Berglund
+3  A: 

Firstly, the using directive is never required in C since C does not support namespaces at all.

The using directive is never actually required in C++ since any of the items found in the namespace can be accessed directly by prefixing them with std:: instead. So, for example:

using namespace std;
string myString;

is equivalent to:

std::string myString;

Whether or not you choose to use it is a matter of preference, but exposing the entire std namespace to save a few keystrokes is generally considered bad form. An alternative method which only exposes particular items in the namespace is as follows:

using std::string;
string myString;

This allows you to expose only the items in the std namespace that you particularly need, without the risk of unintentionally exposing something you didn't intend to.

goldPseudo
A: 

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:

using std::cout;

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

Layne
It is only bad practice in the global namespace in header files. In implementation files it is often a good idea. Saving typing is irrelevant -- your editor should do the typing for you. It's good because it makes code more readable than having `std::` everywhere, and more maintainable than having thirty lines of `using std::whatever;` at the top of every file.
Porculus
+4  A: 

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.

Alexandros Gezerlis
+1  A: 

Namespaces are a way of wrapping code to avoid confusion and names from conflicting. For example:

File common1.h:

namespace intutils
{
    int addNumbers(int a, int b)
    {
        return a + b;
    }
}

Usage file:

#include "common1.h"    
int main()
{
    int five = 0;
    five = addNumbers(2, 3); // Will fail to compile since the function is in a different namespace.
    five = intutils::addNumbers(2, 3); // Will compile since you have made explicit which namespace the function is contained within.

    using namespace intutils;
    five = addNumbers(2, 3); // Will compile because the previous line tells the compiler that if in doubt it should check the "intutils" namespace.
}

So, when you write using namespace std all you are doing is telling the compiler that if in doubt it should look in the std namespace for functions, etc., which it can't find definitions for. This is commonly used in example (and production) code simply because it makes typing common functions, etc. like cout is quicker than having to fully qualify each one as std::cout.

xan
+4  A: 

Technically, you might be required to use using (for whole namespaces or individual names) to be able to use Argument Dependent Lookup.

Consider the two following functions that use swap().

#include <iostream>
#include <algorithm>

namespace zzz
{
    struct X {};


void swap(zzz::X&, zzz::X&) 
{
    std::cout << "Swapping X\n";
}
}

template <class T>
void dumb_swap(T& a, T& b)
{
    std::cout << "dumb_swap\n";
    std::swap(a, b);
}

template <class T>
void smart_swap(T& a, T& b)
{
    std::cout << "smart_swap\n";
    using std::swap;
    swap(a, b);
}

int main()
{
    zzz::X a, b;
    dumb_swap(a, b);
    smart_swap(a, b);

    int i, j;
    dumb_swap(i, j);
    smart_swap(i, j);
}

dumb_swap always calls std::swap - even though we'd rather prefer using zzz::swap for zzz::X objects.

smart_swap makes std::swap visible as a fall-back choice (e.g when called with ints), but since it doesn't fully qualify the name, zzz::swap will be used through ADL for zzz::X.


Subjectively, what forces me to use using namespace std; is writing code that uses all kinds of standard function objects, etc.

//copy numbers larger than 1 from stdin to stdout
remove_copy_if(
    std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
    std::ostream_iterator<int>(std::cout, "\n"),
    std::bind2nd(std::less_equal<int>(), 0)
);

IMO, in code like this std:: just makes for line noise.

I wouldn't find using namespace std; a heinous crime in such cases, if it is used in the implementation file (but it can be even restricted to function scope, as in the swap example).

Definitely don't put the using statement in the header files. The reason is that this pollutes the namespace for other headers, which might be included after the offending one, potentially leading to errors in other headers which might not be under your control. (It also adds the surprise factor: people including the file might not be expecting all kinds of names to be visible.)

visitor
A: 

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.

Alexander Poluektov