The C++ namespace: the anonymous or unnamed namespace and nested namespace C++ code example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Displaying integer to demonstrate the anonymous or unnamed and nested namespace in  C++ programming

To show: How to use the anonymous or unnamed namespace and nested namespace in C++ programming

 

// anonymous or unnamed namespace

#include <iostream>

using namespace std;

 

// anonymous namespace

namespace

{

int p = 1; // unique::p

}

 

void funct1()

{

++p; // unique::++p

}

 

namespace One

{

// nested anonymous namespace

namespace

{

int p; // One::unique::p

int q = 3; // One::unique::q

}

}

 

// using-declaration

using namespace One;

void testing(void)

{

// ++p; // error, unique::p or One::unique::p?

//

// One::++p; //error, One::p is undefined

//

cout<<"++q = "<<++q<<endl;

}

 

int main(void)

{

testing();

 

return 0;

}

 

Output example:

 

++q = 4

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index