Search code examples
c++namespacesunnamed-namespace

Two unnamed namespaces, defined in the same declarative region


Consider the following code:

#include<iostream>

namespace
{
    int a = 5;
}

namespace
{
    int a = 5;
}
int main()
{ 
    int i=5;
    {
        std::cout << i;
    }
}

This code is invalid. It is because redefinition of a is occurred. But I expected that this is valid. Actually, the sec. 3.3.6/1 said:

[...]The potential scope denoted by an original-namespace-name is the concatenation of the declarative regions established by each of the namespace-definitions in the same declarative region with that original-namespace-name.[...]

But unnamed namespace definition is not original-namespace-definition and the sec. 7.3.1/1 said:

namespace-name:
    original-namespace-name
    namespace-alias
original-namespace-name:
    identifier

and

original-namespace-definition:
    inline_opt namespace identifier { namespace-body }

Moreover, the sec. 7.3.1.1 said:

An unnamed-namespace-definition behaves as if it were replaced by

inlineopt namespace unique { /* empty body */ }
using namespace unique ;
namespace unique { namespace-body }

where inline appears if and only if it appears in the unnamed-namespace-definition, all occurrences of unique in a translation unit are replaced by the same identifier, and this identifier differs from all other identifiers in the entire program.

This implies that two unnamed namespaces have the different unique.

Can you explain behavior in the code which I cited?


Solution

  • It's in the very piece you quote:

    all occurrences of unique in a translation unit are replaced by the same identifier

    So all unnamed namespaces in a translation unit are the same one.