Table of Contents

namespace

Syntax:

    namespace name {
    declaration-list;
    }

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 namespace, you'll have to refer to it explicitly or use the using keyword. Example code:

     #include <iostream>
 
     namespace CartoonNameSpace {
       int HomersAge;
       void incrementHomersAge() {
         HomersAge++;
       }
     }
     int main() {
       ...
       CartoonNameSpace::HomersAge = 39;
       CartoonNameSpace::incrementHomersAge();
       std::cout << CartoonNameSpace::HomersAge << std::endl;
       ...
     }

anonymous namespace

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

    namespace {
    declaration-list;
    }

namespace alias

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

   namespace identifier = namespace-specifier;

Related Topics: using