using namespace std; OR std::

May 22, 2013 at 9:58pm
Which is correct? Which one is better/worse? whats wrong with each?

1
2
3
4
5
6
7
8
9
10
#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    return 0;
}


1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
    std::cout << "Hello world!";
    return 0;
}
May 22, 2013 at 10:02pm
They are both technically correct how ever std::cout is better because when you "use" the whole namespace of std it includes a ton of stuff which will slow down your program it's best to only use the things you are actually using. Some of the most common things in the std namespace are
std::string, std::vector, std::array, std::list , std::cout , std::cin , std::getline ,
std::ostream , std::ofstream , std::ALGORITHMS( std::sort, std::min_element...ect )
May 22, 2013 at 10:04pm
Would using the whole namespace be bad for practice?
or is it just preference?
May 22, 2013 at 10:25pm
Bad. The purpose of the namespaces is to decrease the amount of name-conflicts. If you drop it of, you lose that benefit.
May 22, 2013 at 10:30pm
So, from now on I should use std::?
thanks guys,
May 22, 2013 at 11:21pm
As giblit has already said, using using namespace std; at global scope is poor practice as it increases the chance of name collisions (as you import symbols into the global namespace.)

But using std:: all the time can sometimes produce rather cluttered code if you (e.g. using a lot of i/o manipulator to format you output or becuase you're using a number of algorithm in a particulr part of you code.

Luckily there are a few more ways you can deal with the std::

For example, you can...

1
2
3
4
5
6
7
8
9
10
11
12
13
// #1 Import just the symbols you need into the global namespace
//
// Which might make sense as you use cout and endl all over the over
// the place, and the names 'cout' and 'endl' are unlikely to collide.
#include <iostream>
using std::cout; // import just std and endl into the global namespace
using std::endl; // rather than the whole of the standard library

int main()
{
    cout << "Hello world!" << endl;
    return 0;
}


Or you can...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Use using at file scope
//
// While a bit pointless for this hello world program, it might
// be useful for a function that uses a lot of iomanip formatting,
// algorithms, string manipulation functions, or the like.
//
#include <iostream>

int main()
{
    using namespace std;
    cout << "Hello world!" << endl;
    return 0;
}


And of course you can import just the required symbols into the function's scope.

In pactice, I use the prefix approach almost most of the time.

But I do use using at file scope when I feel the need to make a function less cluttered, which isn't bvery often. Other tricks which can hep in this circumstance are typedef-ing and namespace aliasing.

Andy
Last edited on May 22, 2013 at 11:28pm
Topic archived. No new replies allowed.