Coupon Accepted Successfully!


Namespace Scope

C++ allows defining variables with a different scope such as local, global, blocks, classes, functions, etc. This can be done using the keyword namespace introduced by ANSI C++. The C++ standard library is the better example of namespace. All classes, templates, and functions are defined inside the namespace std. In the previous programs, we used the statement using namespace std. This tells the compiler that the members of this namespace are to be used in the current program.

Declaring a Namespace

The namespace can be defined in the programs. The declaration of a namespace is similar to a class declaration except that the namespace is not terminated by a semi-colon. It is declared in the following format:

Declaration of Namespace

namespace namespace_identifier


// Definitions of variables function and classes, etc.



namespace num


int n;

void show (int k) {cout<<k;}


In the above example, the variable n and the function show() are within the namespace scope num. We cannot access the variable m directly. To access the variable and initialize it with a value, the statement would be as follows:

num :: n=50;

Here, n is initialized to 50. The scope access operator is used to access the variable. This method of accessing elements becomes embarrassing. We can also access elements directly using the following declarations:

Accessing namespace

using namespace namespace_identifier // directive statement

using namespace_identifier :: member // declaration method

The first statement allows the access of elements without using a scope access operator.

The second statement allows access to only given elements.

Accessing namespace

using name space num

n=10; // valid statement

show(15); // valid statement

using name space :: n;

m=20; // valid statement

show(14) // invalid statement

Test Your Skills Now!
Take a Quiz now
Reviewer Name