Why is namespace std bad to do?

Why is it bad to use namespace std? I know you can use using std::cout or anything else for that matter or just not use anything like and just have std::(whatever) however why would be bad just to use the whole namespace?

closed account (E0p9LyTq)
http://www.lonecpluspluscoder.com/2012/09/i-dont-want-to-see-another-using-namespace-xxx-in-a-header-file-ever-again/

and http://www.cplusplus.com/forum/unices/27805/
I think I got it lol, I'll always just use (using std::(whatever the thing i need)) from now on. After seeing that I can understand.
You don't have to do std::cout. This is just ugly and a pain.
Use the using declarations.
1
2
3
using std::cout; using std::endl;

cout << "Hello world!" << endl;

Actually, I much prefer to fully specify std::cout; that way I can tell for sure that it is the same cout from namespace std.

Still, there are some times when using or using namespace declarations are good. For example, the Boost libraries have ridiculously long namespace chains, so it saves a lot of typing to use using declarations. It helps that you can scope using declarations, too. Also, sometimes a using namespace is required:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main() {
    using namespace std::string_literals;

    std::string s1 = "Hello\0World";
    std::string s2 = "Hello\0World"s;
    
    std::cout << s1 << '\n' << s2 << '\n';
    return 0;
}
Hello
HelloWorld
Last edited on
closed account (E0p9LyTq)
For long namespace chains someone could use a namespace alias:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

namespace ridiculously_long_and_annoying_namespace_that_is_hard_to_accurately_type
{
   void aFunc()
   {
      std::cout << "This is a namespaced function!\n";
   }
}

namespace foo
{
   namespace bar
   {
      namespace baz
      {
         int qux = 42;
      }
   }
}

int main()
{
   // declare a namespace alias
   namespace ns = ridiculously_long_and_annoying_namespace_that_is_hard_to_accurately_type;
   namespace fbz = foo::bar::baz;

   ns::aFunc();

   std::cout << fbz::qux << '\n';
   return 0;
}
Topic archived. No new replies allowed.