How to use namespace in C++


What are namespaces? and How to use namespace in C++?

In tutorial we will discuss,

What are namesapces in C++ programming language?

What is std namespace in C++ programming language?

How to create our own namespace to avoid global name conflicts?


Namespace is a new concept introduced by the ANSI C++ standards committee.

A namespace is introduced to avoid name clashes (global name conflicts) like re-declaration of variables, method names, class, and structure names.

Syntax for using standard namespace:

using namespace std;

In the above syntax “std” is the namespace where ANSI C++ standard class libraries are defined.

If one wants to use functions like cout, cin, endl etc, he has to include std namespace in his program. Otherwise compiler flag an compile time error.

Even own namespaces can be defined.


namespace namespace_name


//Declaration of variables, functions, classes, etc.


Video Tutorial

Programming exaple to demonstrate the use of namespace:

 using namespace std;
 namespace ns1
     int a = 10;
 namespace ns2
     float a = 20.5;
 int main()
     cout<<"Namespace example"<<endl;
     cout<<"The value of a in ns1 is "<<ns1::a<<endl;
     cout<<"The value of a in ns2 is "<<ns2::a<<endl;
     return 0;


Namespace example
The value of a in ns1 is 10
The value of a in ns2 is 20.5

In the above program we can use cout, endl as we have used the standard namespace that is std in our program.

The ns1 and ns2 are the programmer generated namespaces. To access the value of a from ns1 and ns2 we need to use scope resolution operator.

In this tutorial, we have discussed What are namespaces? and How to use namespace in C++?

If you like the tutorial share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *