Why “using namespace std” is used after including iostream

Danoja Dias
Break the Loop
Published in
3 min readFeb 27, 2019

--

If you are a newbie to C++ and trying to understand a very basic C++ program to print something, you may have this question. You better read this article before going into this. If you have some knowledge of printing in C++, just read this.

First of all, you need to know what C++ namespaces are. In programming, we cannot have variables, functions, etc with the same name. So to avoid those conflicts we use namespaces.

So for one namespace we can have one unique name for variables, functions and that same name can also be used in another namespace. Following example shows two namespaces.

namespace A
{
int x = 5;
void printX()
{
// function statements go here
cout<<x<<endl;
}
}

namespace B
{
int x = 10;
void printX()
{
// function statements go here
cout<<x<<endl;
}
}

We have used the same name for variables and functions here. We can call these A::printX() which will give the result 5 and B::printX() which will give the result 10. There is no naming conflicts since we use two different namespaces. Following code block shows how to use namespaces.

#include <iostream>

using namespace std;

namespace A
{
int x = 5;
void printX()
{
// function statements go here
cout<<x<<endl;
}
}

namespace B
{
int x = 10;
void printX()
{
// function statements go here
cout<<x<<endl;
}
}

int main()
{
A::printX();
B::printX();

return 0;
}

--

--

Danoja Dias
Break the Loop

ATL at Enactor Ltd | Former R&D Engineer at Synopsys Inc | Former Intern at WSO2 | BSc Computer Engineering | GSoC2016 | http://linkedin.com/in/danojadias