Anders Lind
Anders Lind

Reputation: 4830

Are unnamed namespaces legal?

namespace { int Foo (int a); }

Is this code snippet legal? If so, can I reference Foo in anywhere, or only in a certain domain?

Upvotes: 5

Views: 686

Answers (3)

Alok Save
Alok Save

Reputation: 206536

It is legal, You can use Foo anywhere in the same Translation Unit.

Anonymous namespace is the standard prescribed way of saying static on variables to limit their scope to the same Translation unit.

C++03 Standard section 7.3.1.1 Unnamed namespaces

para 2:

The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative.


Update:
As @Matthieu M. correctly points out in the comments, and his answer The C++11 Standard removed the above quote from C++03 Standard, which implies that the static keyword is not deprecated when declaring objects in a namespace scope, Anonymous or Unnamed namespaces are still valid nevertheless.

Upvotes: 9

Matthieu M.
Matthieu M.

Reputation: 299890

The definition changed slightly in the C++11 Standard:

7.3.1.1 Unnamed namespaces [namespace.unnamed]

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

inlineoptnamespace 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.94 [ Example:

namespace { int i; } // unique ::i
void f() { i++; } // unique ::i++

namespace A {
  namespace {
    int i; // A:: unique ::i
    int j; // A:: unique ::j
  }
  void g() { i++; } // A:: unique ::i++
}

using namespace A;

void h() {
  i++; // error: unique ::i or A:: unique ::i
  A::i++; // A:: unique ::i
  j++; // A:: unique ::j
}

—end example ]

Upvotes: 3

Björn Pollex
Björn Pollex

Reputation: 76818

This is legal. You can reference Foo anywhere inside the translation-unit.

From the C++03-standard, Section 7.3.1.1:

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

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

where 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.

The use of the static keyword is deprecated when declaring objects in a namespace scope; the unnamed-namespace provides a superior alternative.

Upvotes: 5

Related Questions