C and C++

Explain Namespace

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 we want to use functions like cout, cin, endl etc, we have to include std namespace in our program. Otherwise compiler flag an compile time error.

Syntax for creating namespace:

namespace namespace_name
{
//Declaration of variables, functions, classes, etc.
}
Example:
#include<iostream>
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;
}
OUTPUT
Namespace example
The value of a in ns1 is 10
The value of a in ns2 is 20.5

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

Leave a comment

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