`namespace` — C++ Keyword

`namespace` — C++ Keyword

The namespace keyword in C++: groups declarations to avoid name collisions.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

namespace

Groups declarations under a named scope, preventing name collisions between libraries and modules.

Syntax

namespace name { declarations }
namespace name::nested { declarations }   // C++17 nested namespace shorthand
namespace { declarations }                // unnamed (anonymous) namespace

Example

#include <print>

namespace math {
    double pi = 3.14159265358979;

    double circle_area(double r) {
        return pi * r * r;
    }
}

// C++17 nested namespace shorthand
namespace app::ui {
    void render() { std::println("rendering"); }
}

// Inline namespace (transparent to outer namespace)
namespace lib {
    inline namespace v2 {
        void func() { std::println("lib v2"); }
    }
}

int main() {
    std::println("{:.4f}", math::circle_area(5.0));
    app::ui::render();
    lib::func();   // resolves to lib::v2::func
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}