62

What is the use of using namespace std?

I'd like to see explanation in Layman terms.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
Jarvis
  • 629
  • 1
  • 6
  • 4

2 Answers2

95
  • using: You are going to use it.
  • namespace: To use what? A namespace.
  • std: The std namespace (where features of the C++ Standard Library, such as string or vector, are declared).

After you write this instruction, if the compiler sees string it will know that you may be referring to std::string, and if it sees vector, it will know that you may be referring to std::vector. (Provided that you have included in your compilation unit the header files where they are defined, of course.)

If you don't write it, when the compiler sees string or vector it will not know what you are refering to. You will need to explicitly tell it std::string or std::vector, and if you don't, you will get a compile error.

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
33

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • Bare in mind there are subtle differences between a *using-directive* and a *using-declaration* in regards to name lookup. – Simple Sep 20 '13 at 10:24
  • @Simple I wanted to keep it simple because Op requested explanation in layman terms. – Ivaylo Strandjev Sep 20 '13 at 10:25
  • 1
    It's also worth mentioning that *using-directives* and *using-declarations* are also subject to scope. Using *using* isn't universally bad. – thokra Sep 20 '13 at 10:51
  • Suppose one wishes to load everything from `std`. How to do? `using std::` only? – Sigur Apr 18 '17 at 01:11
  • if you want to load everything from the namespace you should be write `using namespace std` as I have written in my answer. However you should be aware of the consequences and you should only be using that if you really need it – Ivaylo Strandjev Apr 18 '17 at 07:13