Skip to main content

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.

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.
// 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.
// 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.
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.
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.
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.
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.
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.
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.
int get_dynamic_value();

const int runtime_const = get_dynamic_value(); // Valid
// constexpr int compile_const = get_dynamic_value(); // Error: Not a constant expression
Master C++ with Deep Grasping Methodology!Learn More