1

Is it better programming practice to use the name space std?

Is it better to do this:

std::cout << "hi" << std::endl;

Or this:

using namespace std;

    cout << "hi" << endl;

Why are there two different ways to do this and which way is better programming practice?

EDIT:

I still would like to know why we have two different ways of calling these functions, especially since it is known that issues can arise from using namespace. So why do we even have namespace? Isn't it safer just to call like std::cout. Why do they allow us to use it if it can cause errors?

Dave Cribbs
  • 809
  • 1
  • 6
  • 16
  • IMO The former because `using namespace std;` can introduce subtle hard to find errors. – Galik Oct 12 '14 at 02:36

1 Answers1

4

It depends on the project you're writing. In large projects, namespaces tend to clash - for example if you at some point decided to call your function min(), but wait - there is already std::min() function there which may cause confusion as to which one will be run in some parts of the code.

So, rule of thumb is to use using namespace std; only in rather small projects and use your own namespaces whenever you are writing something bigger than a single file. Definitely, namespace collisions is something we REALLY want to avoid, as it is source of painful bugs.

Additional point would be, that using namespace std; is less harmful in cpp files - especially main.cpp. This can make your code a bit easier to read if you use std functions a lot. Big problem begins, when using namespace ends up in the header file - this header gets included by another header and so on. At some point it is extremely hard to know which namespaces are declared to be used. Thsi is called namespace pollution.

But, again, in main.cpp this should not be the case and it allows to simplify the code, when used properly.

lisu
  • 2,213
  • 14
  • 22
  • I still would like to know why we have two different ways of calling these functions, especially since it is known that issues can arise from using namespace. So why do we even have namespace? Isn't it safer just to call like std::cout. Why do they allow us to use it if it can cause errors? – Dave Cribbs Oct 12 '14 at 02:47