why use namespace std?

Why do some programmers not use the line of code:

 
using namespace std;


Should I not use it? Is it just a short cut for beginners?
closed account (yR9wb7Xj)
I think it depends on your preference. I honestly would find it annoying if I had to type std:: to every single line that needed to be there in order to execute the line of code I want. So I prefer to use using namespace std; because it saves me so much time on writing code, and I honestly think it looks a lot better and cleaner.
Back in the days of C, there were two solutions to the problem of naming functions:
1. Just name it what you think it should be called and pray that no one else has made a different function with the same name.
2. Follow the convention <project>_<function>.
#1 could create conflicts between unrelated libraries that just happened to have functions named the same, and #2 is a bit ugly.

Namespaces are more elegant solution. using namespace in a very broad scope sends you right back to the days of C. You better not make any functions named max, or find, or sort. Two safer alternatives are:
1. Just use what you will use the most. E.g. using boost::filesystem::path;
2. Restrict the using to a more limited scope. E.g.
1
2
3
4
5
6
7
8
void foo(){
    using namespace std;
    cout << "This works.\n";
}

void bar(){
    cout << "This doesn't.\n";
}


Personally, I don't find typing "std::" every time that big a deal. Some Boost namespaces can get rather cumbersome, though.
Last edited on
It is not recommended to use this line, it will cause namespace pollution. The namespace is used to put related things together to avoid naming conflicts. You should use, for example:

std::cout << "Hello" << std::endl;

or

1
2
3
4
using std::cout;
using std::endl;

cout << "Hello" << endl;

http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
Here are some example where using namepaces at global scope could harm you.
And another example of name clash:
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
#include <iostream>
#include <algorithm>
using namespace std;
void func1();
void func2();
int count;

int main()
{
    int i;
    for (i=0; i<10; i++) {
        count = i * 2;
        func1();
    }
}
void func1()
{
    func2();
    cout << "count: " << count;
    cout << '\n';
}
void func2()
{
    int count;
    for(count=0; count<3; count++) std::cout<< '.';
}
Topic archived. No new replies allowed.