# Namespaces and scope

> A scope is the stretch of program text where a declaration can be found by unqualified lookup, and a namespace is a scope you can name, reopen and nest. Points of declaration, shadowing, using-directives and inline namespaces all follow from a few precise rules.

- **Source:** C++ Atlas (https://cppatlas.com/topics/namespaces-and-scope)
- **Track:** Program structure
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [basic.scope.scope] (https://eel.is/c++draft/basic.scope.scope), [basic.scope.pdecl] (https://eel.is/c++draft/basic.scope.pdecl), [basic.scope.block] (https://eel.is/c++draft/basic.scope.block), [basic.namespace] (https://eel.is/c++draft/basic.namespace), [namespace.def] (https://eel.is/c++draft/namespace.def), [namespace.unnamed] (https://eel.is/c++draft/namespace.unnamed), [namespace.alias] (https://eel.is/c++draft/namespace.alias), [namespace.udir] (https://eel.is/c++draft/namespace.udir)
- **cppreference links:** [Scope](https://en.cppreference.com/w/cpp/language/scope), [Namespaces](https://en.cppreference.com/w/cpp/language/namespace), [Namespace aliases](https://en.cppreference.com/w/cpp/language/namespace_alias), [Unqualified name lookup](https://en.cppreference.com/w/cpp/language/unqualified_lookup), [Conflicting declarations](https://en.cppreference.com/w/cpp/language/conflicting_declarations)
- **Prerequisites:** translation-units-and-linkage

## The one idea

Every declaration lives in a **scope**, and from its point of declaration onward, unqualified lookup inside that scope, and inside the scopes nested in it, can find it. Scopes nest: a block inside a function, a function inside a namespace, namespaces inside the global namespace. Lookup walks that nesting from the inside out.

A **namespace** is the one kind of scope you can name, close, and open again later, possibly in another file. Everything else in this topic, from shadowing to inline namespaces, is a consequence of where a scope begins, what it contains, and how using-directives splice one namespace's names into another's lookup.

> **Mental model.** Think of scopes as nested boxes of program text. A name is visible from the point just after its declarator to the end of its box, and an inner box can hide an outer name by declaring the same one.

## The kinds of scope

C++23 lists these kinds of scope in [basic.scope]: the global scope, which is the namespace scope of the global namespace; namespace scopes; class scopes; enumeration scopes; block scopes; function parameter scopes; lambda scopes; and template parameter scopes.

A block scope is introduced by a compound statement, by each selection and iteration statement, and by each exception handler. That is why a variable declared in the condition of an `if`, or in the init-statement of a `for`, is local to the whole statement, including the `else` branch.

The vocabulary changed in C++23. P1787R6, "Declarations and where to find them", rewrote these rules in terms of a declaration **inhabiting** a scope, having a **target scope**, and **binding** a name there. The aim was to fix long-standing defects and inconsistencies while keeping almost all existing code meaning the same thing, and compilers treat most of its fixes as applying to earlier modes too. One related change is visible: P2036R3, adopted for C++23 as a defect report, made a lambda's trailing return type see its own init-captures.

```cpp
#include <type_traits>

void lambda_scope() {
  int x = 0;
  auto f = [x = 2.5]() -> decltype(x) { return x; };  // decltype(x) names the capture
  static_assert(std::is_same_v<decltype(f()), double>);  // passes with GCC 16 and Clang 21
  (void)x;
}
```

## Point of declaration

A name becomes visible at its **locus**, the point of declaration, and the precise location surprises people. For a variable, the locus is immediately after the complete declarator and *before* the initializer. So the declarator still sees the outer name, but the initializer already sees the new one.

```cpp
#include <cstdio>

const int n = 4;

int main() {
  char n[n] = {};                    // array bound uses the outer n: a char[4]
  const int k = 10;
  {
    enum { k = k + 5, m = k * 2 };   // enumerator k is 15, then m is 30
    std::printf("%zu %d %d\n", sizeof n, k, m);  // prints 4 15 30
  }
}
```

Enumerators are different from variables: an enumerator's locus is *after* its initializer, so `k + 5` still reads the outer `k`, while the following `m = k * 2` sees the new enumerator. For a variable, `int v = v;` initializes `v` from itself, so the initializer reads the object's own indeterminate value, which is undefined behavior in C++23.

Other loci worth knowing: a class name is visible right after its name in the class head, so it can appear in its own base-class list, as in CRTP; an alias declaration's name becomes visible only after its type, so `using T = T*;` in an inner scope refers to the outer `T` on the right; and a range-`for` variable is visible only after the range expression, so `for (auto x : x)` iterates over the outer `x`.

Class scope is the exception to "declare before use". Inside member function bodies, default member initializers and default arguments, the whole class is visible, including members declared later. The class is said to be complete in those places.

## Block scope and shadowing

A declaration in an inner block hides any declaration of the same name in enclosing scopes, local or not. A hidden namespace-scope name can still be reached with qualification, such as `::level`, but a hidden local variable cannot be named at all.

```cpp
int level = 0;

int depth() {
  int level = 1;
  {
    int level = 2;            // hides both outer levels; -Wshadow warns
    return level + ::level;   // 2 + 0: the middle level cannot be named from here
  }
}
```

Some redeclarations look like shadowing but are ill-formed. [basic.scope.block] forbids a declaration in the outermost block of a function body from reusing a parameter's name, and a declaration in the body of an `if`, `while`, `for` or `switch` from reusing a name declared in its condition or init-statement. The same applies to a handler's parameter and the handler's outermost block.

```cpp
int get();

void f(int p) {
  // int p = 1;                 // ill-formed: same name as a parameter
  if (int x = get()) {
  } else {
    // int x = 2;               // ill-formed: else shares the condition's scope
  }
  for (int i = 0; i < 3; ++i) {
    { int i = 5; (void)i; }     // OK: a nested block may shadow i
  }
  (void)p;
}
```

> **Pitfall.** Shadowing is legal and silent by default. A local named like a member or a global changes what every later use in the block means. Enable `-Wshadow` in GCC or Clang if your codebase does not deliberately rely on it.

## Namespaces: reopening, nesting, aliases

A namespace definition can be repeated any number of times, in any number of files, and each repetition adds members to the same namespace. A member declared inside a namespace can be defined outside it with a qualified name, but only after it has been declared, and only from a namespace that encloses it.

```cpp
namespace store {
  void save();
}
namespace store { void load(); }    // reopens store

void store::save() {}               // OK: declared above, defined from an enclosing scope
// void store::purge() {}           // ill-formed: purge was never declared in store

namespace store::detail { int retries = 3; }  // C++17 nested namespace definition
```

A **namespace alias** gives an existing namespace a second name, as in `namespace fs = std::filesystem;`. An alias can be used anywhere the namespace name could be used in a qualified name, but it cannot be used to reopen the namespace: `namespace fs { ... }` after the alias is ill-formed.

An **unnamed namespace** behaves as if it were a namespace with a unique name, followed by a using-directive for it. Its members are visible throughout the rest of the translation unit and, since C++11, have internal linkage; the translation-units-and-linkage topic covers the linkage side. Because the members are reached through a using-directive, a name in an unnamed namespace and the same name in the enclosing namespace can coexist, and an unqualified use of it is ambiguous.

## Using-directives and the nearest enclosing namespace

A using-directive such as `using namespace lib;` declares nothing. During unqualified lookup, it makes the members of `lib` appear **as if they were declared in the nearest enclosing namespace that contains both the using-directive and `lib`**. That rule, from [namespace.udir], has a consequence people rarely expect.

```cpp
#include <cstdio>

namespace lib { int value() { return 1; } }

namespace app {
  int value() { return 2; }
  int get() {
    using namespace lib;   // lib's members act as if declared in the global namespace
    return value();        // finds app::value first: returns 2
  }
}

int main() { std::printf("%d\n", app::get()); }  // prints 2
```

The directive is written inside `app::get`, but the nearest namespace enclosing both that function and `lib` is the global namespace. So `lib::value` behaves as a global, and lookup finds `app::value` before reaching it. A using-declaration, `using lib::value;`, would instead declare `value` in the block itself and win.

Using-directives are also transitive: if `B` contains `using namespace A;`, then `using namespace B;` makes `A`'s members visible too. Two directives that bring in the same name are not an error by themselves; only an unqualified use of that name is ambiguous.

> **Standardese.** [namespace.udir] says that during unqualified lookup, the names of the nominated namespace appear as if they were declared in the nearest enclosing namespace that contains both the using-directive and the nominated namespace, and that a using-directive does not add any members to the region in which it appears.

## Inline namespaces and ABI versioning

An **inline namespace**, added in C++11, is a nested namespace whose members also behave as members of the enclosing namespace for most purposes: unqualified and qualified lookup, argument-dependent lookup, and explicit specialization or instantiation of its templates through the enclosing namespace's name. The enclosing namespace and the inline namespace are each associated with the other for ADL.

```cpp
namespace lib {
  namespace v1 { struct Config { int a; }; }
  inline namespace v2 { struct Config { int a, b; }; }

  void load(Config) {}   // Config means lib::v2::Config
}

template <class T> struct Traits;
template <> struct Traits<lib::Config> {};  // specializes for lib::v2::Config

namespace lib::inline v3 {}  // C++20 nested inline namespace syntax
```

The point is that the inline namespace's name still appears in the **mangled names** of its members. `lib::load(lib::v2::Config)` is mangled as `_ZN3lib4loadENS_2v26ConfigE` by GCC 16. Source code says `lib::Config`, but the linker sees the version, so code compiled against `v1` and code compiled against `v2` cannot be silently linked together. Standard libraries use this: libstdc++'s C++11 `std::string` is `std::__cxx11::basic_string`, and libc++ puts the whole library in `std::__1`.

The keyword `inline` must be on the first definition of the namespace. Reopening an inline namespace without it is allowed, but Clang warns; making a namespace inline after it was first defined as non-inline is ill-formed. A name declared both in the enclosing namespace and in its inline namespace makes lookup through the enclosing name ambiguous.

## What to remember

- C++23 scopes: global and other namespace scopes, class, enumeration, block, function parameter, lambda and template parameter.
- P1787R6 rewrote the scope and lookup wording for C++23 with little change in meaning; P2036R3 lets a lambda's trailing return type see its captures.
- A variable is visible from just after its declarator, so `char n[n]` uses the outer `n` and `int v = v;` reads itself.
- An enumerator is visible only after its initializer.
- Inner declarations hide outer ones; hidden globals are reachable with `::`, hidden locals are not.
- Redeclaring a parameter in the function's outer block, or a condition variable in the `if` or `else` body, is ill-formed.
- Namespaces can be reopened; aliases cannot reopen them; qualified definitions need a prior declaration.
- A using-directive makes names act as if declared in the nearest namespace enclosing both the directive and the nominated namespace.
- Inline namespace members act as enclosing-namespace members but keep the inline name in their mangled names, which is how libraries version their ABI.

## Concept Map Outline

- **Namespaces and scope:** Where a declaration is visible, and how named, reopenable namespace scopes combine.
  - **Kinds of scope:** Namespace, class, enumeration, block, function parameter, lambda and template parameter.
    - **Block scopes:** Compound statements, each if, switch, loop and handler introduce one.
    - **P1787R6:** C++23 rewording: declarations inhabit and target scopes and bind names.
    - **P2036R3:** A lambda's trailing return type sees its init-captures; applied as a defect report.
  - **Point of declaration:** The locus where a name starts to be visible.
    - **Variables:** After the declarator, before the initializer: char n[n] uses the outer n.
    - **Enumerators:** After the initializer, so k = k + 5 reads the outer k.
    - **Complete-class contexts:** Member function bodies and default arguments see members declared later.
  - **Block scope:** Inner declarations hide outer ones of the same name.
    - **Shadowing:** Legal and silent; hidden globals are reachable with ::, hidden locals are not.
    - **Forbidden redeclarations:** Parameters in the outer body block, condition names in if or else bodies.
    - **-Wshadow:** GCC and Clang warn about shadowing only when asked.
  - **Namespaces:** Named scopes that can be reopened in any file.
    - **Qualified definitions:** Define a member outside only after declaring it, from an enclosing namespace.
    - **Nested definitions:** namespace a::b::c is C++17; namespace a::inline b is C++20.
    - **Aliases:** namespace fs = std::filesystem; an alias cannot reopen the namespace.
    - **Unnamed namespaces:** A unique name plus a using-directive; same-named globals become ambiguous.
  - **Using-directives:** using namespace N declares nothing; it only changes unqualified lookup.
    - **Nearest enclosing rule:** Names act as if declared in the nearest namespace enclosing directive and target.
    - **Transitive:** A directive for B also brings in namespaces that B nominates.
    - **Ambiguity on use:** Two directives bringing the same name only fail when it is used unqualified.
  - **Inline namespaces:** Members act as members of the enclosing namespace for most purposes.
    - **ABI versioning:** The inline name stays in mangled names, like std::__cxx11 and std::__1.
    - **Specialization:** Templates can be specialized through the enclosing namespace's name.
    - **First definition:** inline must appear on the first definition; adding it later is ill-formed.

## Standardese Quiz Questions

### Question 1 [warmup] ([basic.scope.block], [stmt.select])

Is this function well-formed?

```cpp
int get();

void f() {
  if (int x = get()) {
    (void)x;
  } else {
    int x = 2;
    (void)x;
  }
}
```

A. Well-formed: the `else` block is a new scope, so its `x` shadows the condition's `x`
B. Ill-formed: `x` from the condition cannot be redeclared in the outermost block of the `else` branch
C. Well-formed, but the `else` branch reads the condition's `x`
D. Ill-formed: a variable cannot be declared in an `if` condition

**Answer (B):** Ill-formed: `x` from the condition cannot be redeclared in the outermost block of the `else` branch

**Why:** The condition's `x` belongs to the block scope of the whole `if` statement, which encloses both branches. [basic.scope.block] makes it ill-formed for a declaration in the outermost block of a substatement, such as either branch, to redeclare a name from that enclosing condition. The shadowing answer would be right one level deeper: a nested block `{ int x = 2; }` inside the `else` branch is allowed.

### Question 2 [warmup] ([basic.scope.block], [basic.lookup.unqual], [namespace.qual])

What does `main` return?

```cpp
int level = 0;

int depth() {
  int level = 1;
  {
    int level = 2;
    return level + ::level;
  }
}

int main() { return depth(); }
```

A. 3, because `::level` names the enclosing local
B. 1
C. 2
D. Ill-formed: `level` is redeclared in a nested block

**Answer (C):** 2

**Why:** The innermost `level` is 2, and `::level` is qualified lookup in the global namespace, which finds the global `level` with value 0, so `depth` returns 2. `::` never refers to an enclosing block; once the middle `level` is hidden, there is no way to name it. Redeclaring a name in a nested block is ordinary shadowing, which is legal, although `-Wshadow` warns about it.

### Question 3 [warmup] ([namespace.def], [namespace.alias])

Is this translation unit well-formed?

```cpp
namespace very_long_name { int a; }
namespace v = very_long_name;
namespace v { int b; }
```

A. Well-formed: it adds `b` to `very_long_name`
B. Well-formed: it defines a new namespace `v` that hides the alias
C. Ill-formed: a namespace alias cannot be used to reopen a namespace
D. Ill-formed: aliases may only name nested namespaces

**Answer (C):** Ill-formed: a namespace alias cannot be used to reopen a namespace

**Why:** A namespace definition that reopens a namespace must name the namespace itself, not an alias, and `v` already names an alias in this scope, so it cannot also be a new namespace. GCC and Clang both reject the third line. The first option is the tempting one, because an alias works everywhere else a namespace name does, such as in `v::a`.

### Question 4 [tricky] ([basic.scope.pdecl])

What does this program print?

```cpp
#include <cstdio>

const int n = 4;

int main() {
  char n[n] = {};
  const int k = 10;
  {
    enum { k = k + 5, m = k * 2 };
    std::printf("%zu %d %d\n", sizeof n, k, m);
  }
}
```

A. `4 15 30`
B. `4 5 10`, because the enumerator `k` starts at zero
C. Nothing: `char n[n]` is ill-formed because `n` is used in its own declarator
D. `4 15 20`, because `m` uses the outer `k`

**Answer (A):** `4 15 30`

**Why:** A variable's point of declaration is just after its complete declarator, so the bound in `char n[n]` still sees the global `n` with value 4. An enumerator's point of declaration is after its initializer, so `k + 5` reads the local `const int k`, giving 15, and `m = k * 2` then sees the new enumerator, giving 30. The "ill-formed" option assumes a name is visible as soon as it is spelled, which is true for the initializer but not for the declarator.

### Question 5 [tricky] ([namespace.udir], [basic.lookup.unqual])

What does this program print?

```cpp
#include <cstdio>

namespace lib { int value() { return 1; } }

namespace app {
  int value() { return 2; }
  int get() {
    using namespace lib;
    return value();
  }
}

int main() { std::printf("%d\n", app::get()); }
```

A. `1`, because the using-directive is in the innermost scope
B. Nothing; the call is ambiguous between `lib::value` and `app::value`
C. `2`
D. Nothing; a using-directive is not allowed inside a function

**Answer (C):** `2`

**Why:** During unqualified lookup, a using-directive makes the nominated names appear as if declared in the nearest enclosing namespace that contains both the directive and the nominated namespace. Here that is the global namespace, so `lib::value` behaves like a global and is hidden by `app::value`, which lookup reaches first. The first option treats the directive like a using-declaration; `using lib::value;` in the function would indeed return 1.

### Question 6 [tricky] ([namespace.unnamed], [namespace.udir], [basic.lookup.unqual])

Is this translation unit well-formed?

```cpp
namespace { int counter = 0; }
int counter = 1;

int read() { return counter; }
```

A. Ill-formed: the second line redefines `counter`
B. Well-formed: `read` returns 1, because the global declaration hides the unnamed one
C. Well-formed: `read` returns 0, because the unnamed namespace is searched first
D. Ill-formed: the use of `counter` in `read` is ambiguous

**Answer (D):** Ill-formed: the use of `counter` in `read` is ambiguous

**Why:** An unnamed namespace behaves like a uniquely named namespace followed by a using-directive for it. The global `counter` is a different entity from the one in the unnamed namespace, so the first two lines are fine. In `read`, the using-directive makes the unnamed namespace's `counter` appear as if declared in the global namespace, next to the global `counter`, and the unqualified use is ambiguous. `::counter` does compile and names the global one, because qualified lookup consults using-directives only when the namespace has no such member itself; the unnamed namespace's `counter` then cannot be named from outside that namespace at all.

### Question 7 [standardese] ([namespace.udir], [basic.lookup.general])

Which numbered line makes this translation unit ill-formed?

```cpp
namespace A { int n = 1; }
namespace B { int n = 2; }

using namespace A;                  // (1)
using namespace B;                  // (2)
int first() { return A::n; }        // (3)
int second() { return n; }          // (4)
```

A. (2), because it brings in a second `n`
B. (4)
C. (3), because `A::n` is hidden by the directives
D. None; the most recent directive wins

**Answer (B):** (4)

**Why:** [namespace.udir] says a using-directive adds no members to the scope where it appears; it only affects unqualified lookup. Two directives that bring in the same name are therefore not a conflict by themselves. The ambiguity is only diagnosed when an unqualified use finds both `A::n` and `B::n`, which happens in (4) and makes it ill-formed. The qualified `A::n` in (3) is unaffected.

### Question 8 [standardese] ([namespace.def], [basic.lookup.argdep])

Given `namespace lib { inline namespace v2 { struct Config {}; } }`, which statement is true?

A. `lib::Config` names the type, and its members' mangled names under the Itanium ABI still contain `v2`
B. `lib::Config` names the type, and its mangled names are identical to those of a `Config` declared directly in `lib`
C. A template in `lib::v2` cannot be explicitly specialized using the name `lib::`
D. For an argument of type `lib::v2::Config`, ADL searches `lib::v2` but not `lib`

**Answer (A):** `lib::Config` names the type, and its members' mangled names under the Itanium ABI still contain `v2`

**Why:** Members of an inline namespace can be used in most respects as members of the enclosing namespace: lookup, explicit specialization through the enclosing name, and ADL, where the enclosing namespace is associated as well. The inline namespace is still a real namespace, so it appears in the entity's name and therefore in mangled names, so GCC 16 mangles a function `lib::load(lib::Config)` as `_ZN3lib4loadENS_2v26ConfigE`. That is the whole point of using inline namespaces for ABI versioning, and why the second option is wrong.
