> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/03.-namespaces.md).

# 03. Namespaces

A namespace groups related names (variables, functions, classes) under a label, so identically named things from different parts of a program don't clash.

```cpp
#include <iostream>

namespace test {
    int x = 1;
}

namespace test2 {
    int x = 57;
}

int main() {
    std::cout << test::x << '\n';   // 1
    std::cout << test2::x << '\n';  // 57

    return 0;
}
```

`::` is the **scope resolution operator** — it says "look inside this namespace for this name."

***

### `using namespace`

Instead of typing `std::cout` every time, you can pull an entire namespace into scope:

```cpp
#include <iostream>

using namespace std;

int main() {
    cout << "no more std:: everywhere" << endl;
    return 0;
}
```

You can also pull in just *one* name instead of the whole namespace:

```cpp
#include <iostream>

using std::cout;
using std::endl;

int main() {
    cout << "only cout and endl are unqualified" << endl;
    return 0;
}
```

This second style is often preferred in real projects — you get the convenience without dragging in the *entire* `std` namespace (which can cause name clashes in bigger codebases).

***

### Common mistakes

```cpp
using namespace first;  // ❌ error: no namespace named 'first' exists
std::cout << x;         // ❌ error: x was never declared anywhere
```

You can only `using namespace X;` a namespace that **actually exists** in your code (or a library you included). And a bare variable like `x` only works if it was declared, or explicitly brought into scope.

***

### More cool examples

#### 1. Namespaces for game characters (avoiding name collisions)

```cpp
#include <iostream>

namespace Player {
    std::string name = "Kratos";
    int health = 100;
}

namespace Enemy {
    std::string name = "Goblin";
    int health = 30;
}

int main() {
    std::cout << Player::name << " has " << Player::health << " HP\n";
    std::cout << Enemy::name << " has " << Enemy::health << " HP\n";

    return 0;
}
```

Both namespaces have a variable called `name` and `health` — no conflict, because they live in separate namespaces.

#### 2. Namespaces holding functions

```cpp
#include <iostream>

namespace MathUtils {
    int square(int n) {
        return n * n;
    }

    int cube(int n) {
        return n * n * n;
    }
}

int main() {
    std::cout << "5 squared: " << MathUtils::square(5) << '\n';
    std::cout << "3 cubed: " << MathUtils::cube(3) << '\n';

    return 0;
}
```

#### 3. Nested namespaces

```cpp
#include <iostream>

namespace Company {
    namespace Backend {
        void run() {
            std::cout << "Backend service running...\n";
        }
    }
}

int main() {
    Company::Backend::run();

    // C++17+ shorthand for the same thing:
    // namespace Company::Backend { ... }

    return 0;
}
```

#### 4. Aliasing a long namespace name

```cpp
#include <iostream>

namespace VeryLongCompanyNamespace {
    void greet() {
        std::cout << "Hello from a long namespace!\n";
    }
}

namespace VLC = VeryLongCompanyNamespace; // alias

int main() {
    VLC::greet(); // much shorter to type

    return 0;
}
```

#### 5. Two namespaces, same function name, no conflict

```cpp
#include <iostream>

namespace Celsius {
    double convert(double temp) {
        return temp; // already in Celsius
    }
}

namespace Fahrenheit {
    double convert(double temp) {
        return (temp * 9 / 5) + 32;
    }
}

int main() {
    double tempC = 25;

    std::cout << "Celsius: " << Celsius::convert(tempC) << '\n';
    std::cout << "Fahrenheit: " << Fahrenheit::convert(tempC) << '\n';

    return 0;
}
```

***

### Quick Recap

* `namespace Name { ... }` groups related code under a label.
* Access members with `Name::member`.
* `using namespace X;` imports everything from `X` (convenient, but can cause collisions in big projects).
* `using X::member;` imports just one name — safer middle ground.
* Namespaces can be **nested** and **aliased** (`namespace Short = LongName;`).
* You can't `using` a namespace that doesn't exist, and you can't use a variable that was never declared.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/03.-namespaces.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
