0
Using namespace
why is this used?
2 Answers
+ 3
A namespace is used to avoid name collisions. All identifiers inside a namespace are unique, therefore:
Namespace1::Foo()
is not the same as:
Namespace2::Foo()
with the "using namespace", we can tell the compiler that we will be using a specific namespace during that section of the code. Take "cout" for example. cout is located inside the std namespace. If you want to use cout you must call it like this:
std::cout << "Message";
Or you can call the whole std namespace with "using":
using namespace std;
cout << "Message";
cin >> variable;
We don't need std:: now since we told the compiler we will be using it.
You can also avoid calling the whole namespace and instead just call the function or variable you need:
using std::cout;
cout << "You don't need std here";
std::cin >> variable; //But you do here.
+ 1
AĀ namespaceĀ is a form of scope inĀ C++Ā that holds its own definitions for variables, functions, etc. For example, both cout and cin , along with some useful tokens like endl , are defined inside of std forĀ use. As a result, there are two primary ways to access them. The built inĀ C++Ā library routines are kept in the standard namespace. That includes stuff like cout, cin, string, vector, map, etc. Because these tools are used so commonly, it's popular to add "using namespaceĀ std" at the top of your source code so that you won't have to type theĀ std:: prefix constantly