C++ Programming/Programming Languages/C++/Code/Keywords/namespace

The namespace keyword allows you to create a new scope. The name is optional, and can be omitted to create an unnamed namespace. Once you create a, you'll have to refer to it explicitly or use the   keyword. A namespace is defined with a  block.


 * Syntax:

In many programming languages, a namespace is a context for identifiers. C++ can handle multiple namespaces within the language. By using  (or the   keyword), one is offered a clean way to aggregate code under a shared label, so as to prevent naming collisions or just to ease recall and use of very specific scopes. There are other "name spaces" besides "namespaces"; this can be confusing.

Name spaces (note the space there), as we will see, go beyond the concept of scope by providing an easy way to differentiate what is being called/used. As we will see, classes are also name spaces, but they are not namespaces.


 * Example

Within this block, identifiers can be used exactly as they are declared. Outside of this block, the  specifier must be prefixed (that is, it must be qualified). For example, outside of,   must be written.

C++ includes another construct which makes this verbosity unnecessary. By adding the line  to a piece of code, the prefix   is no longer needed.

unnamed namespace
A  without a name is called an unnamed namespace. For such a, a unique name will be generated for each translation unit. It is not possible to apply the  keyword to unnamed namespaces, so an unnamed namespace works as if the   keyword has been applied to it.


 * Syntax:

namespace alias
You can create new names (aliases) for namespaces, including nested namespaces.


 * Syntax: