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

# Namespaces

Namespaces in C++ are like **"containers"** that group code (variables, functions, classes) to prevent naming conflicts. They act as a **last name** for your code, ensuring that two items with the same name don’t clash. Here’s everything you need to know:

***

#### **1. Why Use Namespaces?**

* **Avoid Naming Conflicts**: If two libraries or code sections have the same name (e.g., `print()`), namespaces keep them separate.
* **Organize Code**: Group related code (e.g., `Math`, `Graphics`).
* **Control Scope**: Limit where identifiers (names) are visible.

***

#### **2. Basic Syntax**

Declare a namespace with `namespace`:

```cpp
namespace Math {
    int add(int a, int b) { return a + b; }
    int subtract(int a, int b) { return a - b; }
}
```

Use the scope resolution operator `::` to access items:

```cpp
int result = Math::add(5, 3); // Result = 8
```

***

#### **3. Nested Namespaces**

Namespaces can be nested for better organization:

```cpp
namespace Game {
    namespace Graphics {
        void render() { /* ... */ }
    }
}

// C++17+ allows this syntax:
namespace Game::Physics {
    void update() { /* ... */ }
}

// Access nested namespaces:
Game::Graphics::render();
Game::Physics::update();
```

***

#### **4. The `using` Directive**

* **Import a Namespace**:

  ```cpp
  using namespace Math; // Import all items from Math
  int result = add(5, 3); // No need for Math::
  ```
* **Import Specific Items**:

  ```cpp
  using Math::add; // Import only the `add` function
  int result = add(5, 3);
  ```

**Warning**: Avoid `using namespace` globally (especially in headers) to prevent conflicts. Use it locally (e.g., inside a function).

***

#### **5. Namespace Aliases**

Shorten long namespace names:

```cpp
namespace VeryLongNamespaceName {
    void doSomething() { /* ... */ }
}

// Create an alias:
namespace Short = VeryLongNamespaceName;
Short::doSomething();
```

***

#### **6. Anonymous Namespaces**

For code that should **only exist in the current file** (like `static` variables):

```cpp
namespace {
    int localVariable = 42; // Only visible in this file
    void helperFunction() { /* ... */ }
}
```

***

#### **7. Best Practices**

1. **Avoid Global `using namespace`**:\
   Never write `using namespace std;` globally in headers—it can cause conflicts.

   ```cpp
   // Bad (global scope):
   using namespace std;
   // Good (local scope):
   void myFunction() {
       using namespace std;
       cout << "Hello!" << endl;
   }
   ```
2. **Use Explicit Names**:\
   Prefer `Math::add()` over relying on `using namespace Math`.
3. **Organize Code**:\
   Group classes/functions into logical namespaces (e.g., `Physics`, `UI`).

***

#### **8. Common Mistakes**

**Conflict Example**:

```cpp
#include <algorithm> // Has std::count

namespace MyLib {
    int count = 0; // Uh-oh! Conflicts with std::count
}

// Fix: Use namespaces explicitly
int main() {
    int count = MyLib::count; // Safe
    std::vector<int> v;
    std::count(v.begin(), v.end(), 5); // Safe
}
```

***

#### **9. Where to Learn More**

* **cppreference.com**: [Namespaces in C++](https://en.cppreference.com/w/cpp/language/namespace)
* **C++ Primer (Book)**: Chapter 2.5 (Namespaces)
* **LearnCpp.com**: [Lesson 6.2](https://www.learncpp.com/cpp-tutorial/namespaces/)
* **ISO C++ FAQ**: [Namespaces](https://isocpp.org/wiki/faq/cpp-11-language#namespace)

***

#### **10. Real-World Example**

Imagine two libraries for logging and math:

```cpp
namespace Logger {
    void log(const std::string& message) { /* ... */ }
}

namespace Math {
    const double PI = 3.14159;
    double calculateArea(double radius) { return PI * radius * radius; }
}

int main() {
    Logger::log("Calculating area...");
    double area = Math::calculateArea(5.0);
    Logger::log("Area: " + std::to_string(area));
    return 0;
}
```

***

#### **Key Takeaway**

Namespaces are essential for organizing code and avoiding conflicts. Use `::` to access items, limit `using namespace` to local scopes, and group related code logically.


---

# 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:

```
GET https://42-guide.gitbook.io/42-guide/all-about-c++/namespaces.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
