`const` — C++ Keyword

`const` — C++ Keyword

The const keyword in C++: marks a variable or member function as non-modifiable.

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.

const

Marks an object as non-modifiable. On a member function, it guarantees the function does not modify the object's observable state.

Syntax

const Type name = value;          // const object
const Type& ref = expr;           // const reference (read-only alias)
const Type* ptr = &obj;           // pointer to const (target is read-only)
Type* const ptr = &obj;           // const pointer (address is fixed)
const Type* const ptr = &obj;     // both pointer and target are const

return-type func() const;         // const member function

Example

#include <print>

class Circle {
public:
    explicit Circle(double r) : r_(r) {}

    double area() const {             // const member: cannot modify r_
        return 3.14159 * r_ * r_;
    }

private:
    double r_;
};

int main() {
    const double pi = 3.14159;        // cannot be reassigned
    // pi = 3.0;   // error

    const Circle c{5.0};
    std::println("{:.4f}", c.area()); // OK: area() is const
}

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;
}