Skip to main content

Simple Example Program For Namespace In C++

1 min read Updated June 30, 2026
Share:
On this page (8sections)

Definition

A namespace (sometimes also called a name scope) is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols (i.e., names). An identifier defined in a namespace is associated only with that namespace. The same identifier can be independently defined in multiple namespaces. That is, the meaning associated with an identifier defined in one namespace may or may not have the same meaning as the same identifier defined in another namespace. Languages that support namespaces specify the rules that determine to which namespace an identifier (not its definition) belongs.

The functionality of namespaces is especially useful in the case that there is a possibility that a global object or function uses the same identifier as another one, causing redefinition errors.

Namespace Syntax

namespace abc {
 int variable;
}

Adding Namespace:

using namespace abc;

Usage Namespace Member:

abc::variable

Namespace Example Program

/*  Example Program For namespace Example In C++
    little drops @ thiyagaraaj.com

    Coded By:THIYAGARAAJ MP             */

#include <iostream>
using namespace std;

//Namespace namespace first
namespace namespacefirst {
    int value = 5;
}

//Namespace namespace second
namespace namespacesecond {
    double value = 3.1416;
}

int main() {
    //Namespace namespace first Variable Usage
    cout << "namespacefirst value : " << namespacefirst::value << endl;

    //Namespace namespace second Variable Usage
    cout << "namespacesecond value : " << namespacesecond::value << endl;
    return 0;
}

Sample Output

namespace first value: 5
namespace second value: 3.1416

Learn the concept first, then study the code:

Frequently Asked Questions

What does this C++ program do?
It is a C++ example program that demonstrates Simple For Namespace, including the complete source code and the expected sample output.
How do I compile and run this C++ program?
Save the code in a `.cpp` file, compile it with `g++ filename.cpp -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses core C++ syntax, illustrating a common pattern in C++ programming.

Related Tutorials

Search tutorials