3

Possible Duplicate:
Ordering of using namespace std; and includes?

I heard that it is strongly prohibited to use "using namespace xy" before "#include ". E.g.

#include <iostream>

using namespace std;

int main() {
...
}

What's the technical reason for that? I tried following and it worked without any problems:

using namespace std;

#include <iostream>

int main() {
....
}
Community
  • 1
  • 1
netsplit
  • 140
  • 1
  • 10

3 Answers3

3

No, it is not strongly prohibited (otherwise it would be a compilation or preprocessing error).

The using keyword puts all functions and variable into the current namespace, and it is discouraged to use it in the header files.

BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • 1
    +1 for `it is discouraged to use it in the header files`; because in `.cpp` file it's ok to use (not always a bad practice). – iammilind Aug 01 '11 at 07:27
3

I can think of one good reason. It is that if the namespace hasn't already been declared, the statement is illegal. At least by my reading of the standard; most compilers seem to treat the using directive (using namespace name;) as if it was a declaration of the namespace, although there's nothing in the standard that I can find to justify this.

More generally, it's best to avoid namespace directives as much as possible, except in very limited scopes (and I'd never use a namespace directive for std, because there's just too much in it which would get drawn in).

James Kanze
  • 150,581
  • 18
  • 184
  • 329
2

The technical reason is that using will only import anything that is currently visible into the current namespace.

If you're includeing a file after using, you introduce a "weird" order dependency. Of course, this could be what you want, so it is not forbidden by the language. However, you're effectively changing the meaning of headers you're including after the using, since you're exposing the header to a different context (and name lookup might find other names, depending on the context). Name lookup rules can sometimes be subtle, and you don't want to introduce subtleties in someone else's code.

There's an excellent discussion of this in the book "C++ Coding Standards" (Sutter, Alexandrescu), Chapter 59: "Don't write namespace usings in a header file or before an #include"

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
ltjax
  • 15,837
  • 3
  • 39
  • 62
  • 1
    This is true for a using declaration, but not for a using directive, which is what's being discussed here. "for each using-directive (7.3.4) that nominates the member’s namespace, the member’s potential scope includes that portion of the potential scope of the using-directive that follows the member’s point of declaration." The name doesn't have to be in scope before the using directive. – Ben Voigt Aug 07 '11 at 02:04