In C++ programming language all the names that are used in standard library are defined in namespace std. In Turbo C++ compiler we do not use namespace for standard library functions; however, namespace is used in visual C++.
There are two methods for using namespace std that is in directive using or we can use it in cout and cin statements as follows:
std :: cout << “Enter a number “;
std :: cin >> n;
The use of using directive is not necessary here. However the syntax of using directive is as follows:
using namespace std;
this is used after the header file # inlcude<iostream>.
The namespace is used to separate the names used in one part of program from other. In C++ programming language we can define our own namespace name.
The syntax of declaring a namespace uses the keyword namespace as follows:
//this is the code that will be in the namespace myown
A namespace cannot be declared inside a function. Namespaces are used to contain variables, functions and other members in the program.
Namespaces should always be declared globally that is before the main function, because the execution of the program starts with the main function therefore, the compiler will generate an error if the namespace are not globally declared. Or the compiler will not recognize namespace.
Consider the following example to understand the concept of namespace.
# include <iostream.h >
# include <conio.h>
int x =0;
void main ()
std :: cout << “enter a number “;
std :: cin >> myown :: x;
std :: cout << myown :: x;
Working of above program:
In the above program, a namespace myown has been declared which contains a variable x that is initialized at zero. In the main function the cout statement is used to enter an integer that is to be stored in the variable x declared in myown namespace. ( :: ) is a scope resolution operator that tells the compiler which function or variable is to be called.
Here the variable of namespace myown is called and the value entered by the user as an input is stored int this variable. After this the entered value is printed using cout statement and scope resolution operator that calls the namespace myown.
In C++ programming, we can declare more than one namespace, the name of the namespaces should be different.
The functions or variables of the respective namespaces are called by using scope resolution operator that enables the compiler which function or variable is to be called or used.