const

The const Keyword in C++

Learn what the const keyword does in C++, how it applies to variables, pointers, references and member functions, and how the compiler enforces it.

On this page
  1. What const means in C++
  2. Declaring a const variable
  3. Compiler messages for const errors
  4. const and pointers
  5. const references
  6. const member functions
  7. const at namespace scope
  8. const_cast
  9. const versus constexpr
  10. Common mistakes
  11. When to use const

What const means in C++

The const keyword marks a variable or object as read-only once it has its value. If code tries to change it, the compiler stops with an error. That turns a hope like “this value shouldn’t change” into a rule the compiler checks.

const int max_players = 4;

max_players = 5;  // Compile error: max_players is read-only

Declaring a const variable

const can go before or after the type. For a plain variable, both forms mean the same thing:

const double tax_rate = 0.07;
int const retries = 3;  // same meaning as: const int retries = 3;

A const object must be initialized when you declare it, because you can’t assign to it later:

const int width;       // Compile error: no initial value
const int width = 80;  // OK

Compiler messages for const errors

The exact wording depends on the compiler. GCC usually reports an assignment of a read-only variable, and Clang says it cannot assign to a variable with a const-qualified type. Some compilers use the phrase “expression must be a modifiable lvalue” for the same kind of problem. Each message means the same thing: the target of an assignment has to be something you’re allowed to change.

When you see one of these errors, decide whether the value should really change. If it should, remove const from that variable. If it shouldn’t, change the code that tries to write to it. For a deeper look at the last message, see c expression must be a modifiable lvalue.

const and pointers

Pointers are where const placement matters most. A const written before the * applies to the value the pointer points to. A const written after the * applies to the pointer itself:

int value = 10;
int other = 20;

const int* p1 = &value;  // pointer to const int
int* const p2 = &value;  // const pointer to int

p1 = &other;  // OK: p1 can point somewhere else
*p1 = 30;     // Error: the int can't be changed through p1
*p2 = 30;     // OK: the int itself can change
p2 = &other;  // Error: p2 always points to value

You can combine both forms with const int* const p3 = &value;. Through p3, neither the pointer nor the value it points to can change. The original value can still be changed directly, because const on a pointer only limits access through that pointer.

const references

A const reference lets a function read an object without copying it and without changing it. This is common for function parameters:

#include <iostream>
#include <string>

void print_name(const std::string& name) {
    std::cout << name << "\n";
    // name = "Ana";  // Error: name is a const reference
}

int main() {
    std::string player = "Ana";
    print_name(player);
    print_name("Ben");  // A const reference can bind to a temporary string
}

For small types such as int or double, passing by value is usually fine. Reserve const references for types where copying costs something, such as strings and larger objects.

const member functions

Putting const after a member function’s parameter list promises that the function won’t change the object’s data members:

class Counter {
public:
    int value() const { return count; }  // reads only
    void increment() { ++count; }        // changes the object

private:
    int count = 0;
};

int main() {
    const Counter c{};
    std::cout << c.value() << "\n";  // OK: value() is const
    // c.increment();                // Error: increment() is not const
}

A const object can call only its const member functions. A const member function can still be called on a non-const object. Data members marked mutable can change even inside a const member function. Use mutable sparingly, for things such as an internal cache.

const at namespace scope

A const variable at global or namespace scope has internal linkage in C++. That means each source file that includes it gets its own copy. A const defined in a header is therefore safe to include in several files, though each file has a separate object.

C++ also lets a const integer initialized with a constant value serve as an array size:

const int grid_size = 5;
int cells[grid_size] = {};  // OK in C++

C handles this differently. At file scope, a const variable in C can’t be used as an array size, so the same code doesn’t compile there.

const_cast

const_cast can remove const from a pointer or a reference. You may see it in older code that calls a function which takes a non-const pointer but doesn’t change the data. Removing const and then changing an object that was originally defined as const is undefined behavior. When you can, fix the function’s signature instead. Avoid const_cast as a shortcut around a compile error.

const versus constexpr

const means the value can’t change after it’s initialized. The initial value can be computed at run time:

const int n = get_size_from_user();  // fine: the value is set at run time

constexpr means the value must be known at compile time:

constexpr int buffer_size = 256;  // the compiler must know this value

Use constexpr when the compiler needs the value itself, and const when a value just shouldn’t change after it’s set.

Common mistakes

  • Declaring a const variable without giving it a value.
  • Confusing const int* with int* const, which changes what the code may do with the pointer.
  • Calling a non-const member function on a const object or through a const reference.
  • Leaving const off a member function that only reads data, so const objects and const references can’t use it.
  • Reaching for const_cast to silence an error without checking whether the object really is const.

When to use const

Mark a variable const when its value should not change after setup. Take parameters as const references when a function only reads them. Mark member functions const when they don’t change the object. These habits catch mistakes at compile time and show other readers what the code is meant to do.

Keep exploring

Guides from other topics

All topics →

How to Stringify a Macro in C++

Learn how the # operator turns a C++ macro argument into a string literal, with examples, the two-level trick for expanded macros and common pitfalls.

Macros 3 min read

Polymorphism in C++

Learn polymorphism in C++ with clear code examples: virtual functions, override, abstract classes, templates, and the mistakes beginners make most often.

Polymorphism 7 min read