Using Keyword
In
the previous section, you must have noticed that each time we refer to a
namespace variable you have to make use of scope resolution operator. You also
need to specify the namespace. Doing this repeatedly is a tedious job,
especially if you are going to make use of a particular namespace frequently.
The best solution is to use the keyword using.
What
about namespace std?
The std
namespace is the area in which the entire Standard C++ library is declared.
Remember how we start our programs :
#include <iostream>
using std namespace;
int main ( )
{ ...
}
Using
statement informs the compiler that you want to use the std
namespace. The keywords cout, cin etc... are all
present in the std namespace.
Some C++ textbooks make use of the following way of writing programs :
#include <iostream>
int main ( )
{
int x = 10;
std :: cout<<x;
return 0;
}
Generally we don't
use this method because we will use cout and cin
very frequently in our coding. By the above method you will have to use
std :: each time you use cout or cin.
It is very convenient to make use of using std namespace; before
the main ( ) function.
There
are two methods to make use of the using keyword :
using namespace name;
example : using namespace counterspace;
using name :: member; example : using counterspace :: increment;
In the
first case, you don't need to make use of scope resolution when you are
referring to any variable or function belonging to namespace counterspace.
In the second case, only the variable increment is
made visible. Check out the example below:
#include <iostream>
using namespace std;
namespace increment
{
int i;
int operate (int a)
{
return ++a;
}
}
namespace decrement
{
int j;
int operate (int a)
{
return --a;
}
}
int main ( )
{
int k;
cout<<"Enter the number you want to operate on : ";
cin>>k;
using namespace increment;
cout<<endl<<"Decremented value is : "<<decrement : : operate(k);
cout<<endl<<"Enter the value of i : ";
cin>>i;
cout<<endl<<"Value of i is "<<i;
return 0;
}
In the main ( )
function, we have said using namespace increment.
i is a variable belonging to increment
namespace and so you don't need the scope resolution operator. Suppose you want
to refer to the operate ( ) function of the
namespace decrement, then you have to explicitly
say so (using scope resolution).
If
you have any doubts, then feel free to email me.
Go on to the next section on : Command Line Arguments
or go back to Contents2