Why “using namespace std” is used after including iostream

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 and that same name can also be used in another namespace. Following example shows two namespaces.

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 namespaces. Following code, block shows how to use namespaces.

?using namespace std? means we use the namespace named std. ?std? is an abbreviation for standard. So that means we use all the things with in ?std? namespace. If we don?t want to use this line of code, we can use the things in this namespace like this. std::cout, std::endl.

If this namespace is not used, then computer finds for the cout, cin and endl etc.. Computer cannot identify those and therefore it throws errors.

So now you have an idea on namespaces. Let?s go to the original question why namespace is used, when we have all in the iostream header file. iostream is a file that has all the things like cout, endl and etc is defined. If we need to use them we need to add that file. So basically #include <iostream> means copying and pasting the code in that file to your code. But if we try to use cout, endl in our code without specifying the namespace it will throw an error, because these are defined in the std namespace in the iostream.h file like following. Following is dummy of iostream.h file. This will give you an idea about how this is defined.

So when we run a program to print something, ?using namespace std? says if you find something that is not declared in the current scope go and check std.

So now you have the answer why both statements

#include <iostream>using namespace std;

are used. It is because computer needs to know the code for the cout, cin functionalities and it needs to know which namespace they are defined.

So as a summary, why you need both the header file and the namespace to run a simple c++ program, because computer needs to know the definition of the code of the functionalities. It is defined in the header file. So header file needs to be included. namespace is needed because if a functionalities like cout is used, but not defined in the current scope computer needs to know where to check. so namespace needs to be included. Because we are writing the code outside the std namespace.


No Responses

Write a response