> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# C++ Const Variable

A `const` variable in C++ is a strongly typed identifier whose value is evaluated and locked at initialization, rendering it immutable throughout its lifecycle. The compiler enforces this immutability by emitting a diagnostic error if any subsequent assignment or state modification is attempted.

## Syntax and Initialization

Because a `const` variable cannot be assigned a value after creation, it must be initialized at the point of declaration. C++ supports two syntactical placements for the `const` qualifier: "West const" (before the type) and "East const" (after the type). Both are semantically identical.

```cpp theme={"dark"}
// Valid initializations
const int max_connections = 100; // West const
int const timeout_ms = 5000;     // East const

// Compiler Error: uninitialized const
const double pi; 
```

## Linkage Rules

By default, `const` variables declared at namespace scope (global scope) possess **internal linkage**. This means they are implicitly `static` and visible only within the translation unit in which they are defined.

To give a `const` variable external linkage (making it accessible across multiple translation units), it must be explicitly declared with the `extern` keyword in both the declaration and the definition.

```cpp theme={"dark"}
// header.h
extern const int global_status; // Declaration

// source.cpp
extern const int global_status = 1; // Definition
```

## Const and Pointers

When combining `const` with pointers, the placement of the `const` keyword relative to the asterisk (`*`) dictates whether the pointer itself, the data being pointed to, or both are immutable.

**1. Pointer to Const**
The data cannot be modified through the pointer, but the pointer can be reassigned to a different memory address.

```cpp theme={"dark"}
int value1 = 10;
int value2 = 20;
const int* ptr = &value1; 
// *ptr = 15; // Error: Cannot modify pointee
ptr = &value2; // Valid: Can reassign pointer
```

**2. Const Pointer**
The pointer is locked to a specific memory address, but the data at that address can be modified.

```cpp theme={"dark"}
int value = 10;
int value2 = 20;
int* const ptr = &value;
*ptr = 15; // Valid: Can modify pointee
// ptr = &value2; // Error: Cannot reassign pointer
```

**3. Const Pointer to Const**
Both the memory address and the underlying data are strictly immutable.

```cpp theme={"dark"}
int value = 10;
int value2 = 20;
const int* const ptr = &value;
// *ptr = 15; // Error: Cannot modify pointee
// ptr = &value2; // Error: Cannot reassign pointer
```

## Const References

A `const` reference (`const T&`) binds to an object and prevents modification of that object through the reference. Crucially, C++ allows `const` references to bind to temporary objects (rvalues), extending the lifetime of the temporary to match the lifetime of the reference.

```cpp theme={"dark"}
const int& ref = 42; // Valid: Lifetime of temporary '42' is extended
// int& bad_ref = 42; // Error: Non-const reference cannot bind to an rvalue
```

## Const Class Members

When a class contains a `const` member variable, it cannot be assigned a value inside the constructor body. It must be initialized either directly at the point of declaration using an in-class initializer (since C++11) or via the constructor's **member initializer list**.

```cpp theme={"dark"}
class Server {
    const int max_retries = 3; // Valid: C++11 in-class initializer
    const int port;
public:
    // Valid: Initialized via member initializer list
    Server(int p) : port(p) {} 

    /* 
    // Error: Assignment of read-only member
    Server(int p) {
        port = p; 
    }
    */
};
```

## Const Member Functions

Applying the `const` qualifier to the end of a class member function declaration enforces that the method will not modify the observable state of the object. A `const` member function is prohibited from modifying any non-`static` and non-`mutable` member variables. Furthermore, if a class instance is declared as `const`, the compiler will only allow the invocation of its `const` member functions.

```cpp theme={"dark"}
class DataStore {
    int data = 0;
public:
    void set_data(int v) { data = v; } // Non-const function
    
    int get_data() const { 
        // data = 5; // Error: Cannot modify member in a const function
        return data; 
    }
};

const DataStore store;
// store.set_data(10); // Error: Cannot call non-const function on a const object
int val = store.get_data(); // Valid: get_data is a const member function
```

## Const vs. Constexpr

While `const` guarantees immutability, it does not guarantee compile-time evaluation. A `const` variable can be initialized with a value only known at runtime. If strict compile-time evaluation is required, C++11 introduced `constexpr`, which implies `const` but forces the initialization to occur during compilation.

```cpp theme={"dark"}
int get_dynamic_value();

const int runtime_const = get_dynamic_value(); // Valid
// constexpr int compile_const = get_dynamic_value(); // Error: Not a constant expression
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor C++ Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
