why do we say "using namespace std;"

In all of the programs I've written for practice and school I've had to say
1
2
#include <iostream>
using namespace std;


I know the reason why I always have to say #include <iostream> is because I always write console applications and that header is necessary in order for the compiler to understand the cin and cout commands but why must I also write using namespace std;

I tried googling why and found this in an archived thread on here. (since it was archived I couldn't reply to it)
Catfish wrote:
f you don't write using namespace std; you will have to explicitly add std:: before anything in the std namespace.

Example:
1
2
3
std::cout << "Hello World!" << std::endl;
std::string s;
std::vector<std::string> vs;


Some people, myself included, prefer to write std::.


Ok but why would you need to do that? What would happen if you didn't write the header using namespace std; nor did you put std; after every statement in your program? Would you get a compile error and if so why?
I read this somewhere, it has to do with options concerning the library I think I'd have to find and 're read it to know.
Of course you will get a compile to error because All the files in the C++ standard library declare all of its entities within the std namespace. That is why we have generally included the using namespace std; statement in all programs that used any entity defined in iostream. to use them we need to declare using namespace std;.
First you sould read about namespaces and what they are used for.
One starting point is http://www.cplusplus.com/doc/tutorial/namespaces/ .
Long story short, namespaces were created so that you can have the same name for functions/variables/classes/ and not have conflics. Supose you need to create your own string class but use the standard one to, you would not be able to do so in C for example. So to help you have have your own class with names that might conflict with others, you use a namespace, when you need to use your own you use my_namespace::string, when you need to use the standard one you use std::string.
So to answer your question, you use that because all the classes functions, and anything from the standard templete library is declared withing the std namespace.

Look at this post http://www.cplusplus.com/forum/beginner/90715/#msg488279 for an example of namespace usage
Last edited on
the purpose of a namespace is to avoid name clash

using namespace std; voids this effort
Topic archived. No new replies allowed.