Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 171 ยท Pointers, References and Memory

const with Pointers and References

Learn C++ const with pointers and references - pointer to const vs const pointer, reading declarations right to left, const_cast dangers and const correctness.

A pointer involves two objects: the pointer itself and the thing it points to. So when you add const, there are two different things you might be promising not to change. const int* p promises not to change the int through p. int* const p promises not to change p itself. const int* const p promises both. Mixing these up is one of the most common sources of confusing compiler errors in C++.

This lesson gives you a reliable way to read any declaration, shows how the rules carry over to references, and explains const correctness: the habit of marking everything that shouldn't change as const, so the compiler can catch mistakes and readers can trust your function signatures. You should be comfortable with Pointers and References, and you've already met plain const variables in Constants.

Two things can be const

Here are the four combinations side by side. The comments show what each declaration allows.

C++
int value = 1;
int other = 2;

int* p1 = &value;               // change *p1: yes   change p1: yes
const int* p2 = &value;         // change *p2: NO    change p2: yes
int* const p3 = &value;         // change *p3: yes   change p3: NO
const int* const p4 = &value;   // change *p4: NO    change p4: NO
  • Pointer to const (const int*): a read-only view. You can move the pointer to other objects, but you can't modify what it points at through this pointer.
  • Const pointer (int* const): the pointer is locked to one address forever (so it must be initialized), but the object can be changed through it.
  • Const pointer to const (const int* const): both locked.

Try uncommenting each "error" line in the program below to see what the compiler says.

C++ The four kinds of pointer const-ness

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last two lines reveal something subtle: const int* means "I won't change it through this pointer", not "nobody will change it". value is an ordinary int, so code that has non-const access can still modify it, and *locked sees the new value 99. A pointer to const is a promise about access, not a guarantee about the object.

Reading declarations right to left

The reliable trick is to read the declaration from the variable name outward, right to left, saying "pointer to" for each *:

Declaration Read right to left
int* p p is a pointer to int
const int* p p is a pointer to int that is const โ†’ pointer to const int
int const* p p is a pointer to const int (same as above)
int* const p p is a const pointer to int
const int* const p p is a const pointer to const int
const int** pp pp is a pointer to a pointer to const int
int* const* pp pp is a pointer to a const pointer to int

The key rule underneath: const applies to whatever is immediately to its left. If nothing is to its left, it applies to what's immediately to its right. So const int* and int const* are identical: the const sticks to int either way. What matters is whether the const is before or after the *.

  • const before the * โ†’ the pointed-to object is const.
  • const after the * โ†’ the pointer itself is const.

Some codebases write "east const" (int const*) precisely so that the right-to-left reading always works; most write "west const" (const int*) because it reads like English. Both are correct. Be consistent within a project.

Type aliases can make this surprising. With using IntPtr = int*;, the declaration const IntPtr p is a const pointer to int (int* const), not a pointer to const int, because const applies to the whole aliased type. This is one reason to avoid hiding pointers behind aliases.

Conversions: adding const is free, removing it isn't

You can always convert a T* to a const T*: adding a restriction is safe. The reverse doesn't happen implicitly, because it would let you write to something you promised not to modify.

C++ Adding const is implicit, removing it is an error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The same rule makes string literals safe: a literal like "hello" has type const char[6], so it converts to const char* but not to char*. Old C code that writes char* s = "hello"; doesn't compile as C++11 or later.

Pointers to pointers are stricter

You might expect int** to convert to const int**. It doesn't, and the reason is instructive. If it were allowed, you could use the const int** to store the address of a real const int into an int*, and then modify the constant through that int*. The safe conversion is int** โ†’ const int* const*, where the middle pointer is const too. You'll rarely hit this, but if you do, now you know the compiler is protecting you, not being difficult.

const and references

References can't be reseated, so there's no "const reference" in the sense of int* const: every reference is already locked to its object. The only meaningful const with references is reference to const: const T&.

C++
int score = 7;
const int& view = score;    // read-only alias
// view = 8;                // error: assignment of read-only reference 'view'
score = 8;                  // fine, and view sees 8
int& const weird = score;   // error: 'const' qualifiers cannot be applied to 'int&'

People often say "const reference" when they mean "reference to const". That's fine in conversation, since the other meaning doesn't exist. As you saw in References, const T& can also bind to temporaries, which a plain T& can't.

Const correctness in function signatures

Const correctness means: whenever a function only reads something, its parameter type says so. The payoff is threefold:

  1. The compiler catches accidents. An accidental write to a read-only parameter is a compile error, not a bug report.
  2. Callers can pass const objects and temporaries. A function taking std::string& can't accept a literal or a const std::string; one taking const std::string& can.
  3. Signatures document intent. void print(const Report&) tells the reader at a glance that the report isn't changed.
C++ A const-correct interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A few habits professionals follow:

  • Large inputs โ†’ const T&. Small inputs (int, double, pointers, std::string_view, std::span) โ†’ by value. Marking a by-value parameter const (void f(const int x)) only affects the function's own body and isn't part of the signature; many style guides skip it in declarations.
  • Non-owning, read-only pointers โ†’ const T*. A T* parameter should be a signal that the function modifies the object.
  • Return const T* or const T& when handing out a view into your data that callers must not change.
  • Views of elements in loops โ†’ const auto&.
  • Member functions that don't change the object get const after the parameter list. That's a big topic of its own, covered in const Member Functions and mutable.

const spreads, and that's good

Once some code is const-correct, its callers need to be too: a function receiving a const Item& can only call other functions that accept const Item& (or copies). Programmers sometimes call this "const poisoning", but it's really the type system doing its job. Start const-correct from day one; retrofitting it later is painful.

const_cast: breaking the promise

const_cast removes (or adds) const from a pointer or reference type. It exists for one legitimate purpose: calling old APIs that take T* even though they never write to it.

C++ const_cast for a legacy function that only reads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The danger is in the rule: modifying an object that was defined const is undefined behavior, even through a const_cast. In the program above, writing through the cast pointer is fine only because real_value was never const. If you did the same to a const int or to the characters of a string literal, anything could happen: the constant might live in read-only memory (crash), or the compiler might have already substituted its value everywhere (the write is silently ignored).

If you find yourself reaching for const_cast in new code, stop and fix the design instead. The legitimate uses are interfacing with const-incorrect legacy code and a few well-known idioms (like implementing a non-const member function in terms of its const twin). It is never a way to change something that is really constant.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. int a = 1, b = 2; const int* p = &a; Which statement compiles?

    p is a pointer to const int. You can't write through it, but the pointer itself isn't const, so it can be pointed at b.
  2. 2. What is int* const p when read right to left?

    The const comes after the *, so it applies to the pointer. p must be initialized and can't be reseated, but *p can be modified.
  3. 3. int x = 5; const int* p = &x; x = 6; What is *p now?

    const int* only restricts access through p. x itself isn't const, so it can change, and p sees the new value.
  4. 4. Which conversion happens implicitly?

    Adding const at the first level is always safe. Removing it requires a cast, and int** to const int** is rejected because it could be used to break const.
  5. 5. const int limit = 10; *const_cast<int*>(&limit) = 20; What does the standard say?

    const_cast compiles, but writing to an object that was originally defined const is undefined behavior. The program might crash or ignore the write.

Summary

  • A pointer has two things that can be const: the pointee and the pointer. const int* (pointer to const) vs int* const (const pointer) vs const int* const (both).
  • Read declarations right to left from the name. const applies to what's on its left, or to its right if nothing is on its left; const int* equals int const*.
  • A pointer or reference to const restricts access through that name; the object itself may still change through other paths.
  • Adding const (T* โ†’ const T*) is implicit; removing it needs const_cast. String literals are const char arrays.
  • References are never reseatable, so the only useful form is const T& ("reference to const").
  • Const correctness: take read-only inputs as const T&/const T*/views, use non-const only when you modify, and mark read-only member functions const.
  • const_cast is for const-incorrect legacy APIs. Modifying an object defined const is undefined behavior.

Next: Dynamic Memory: new and delete, where pointers meet the heap and you'll see why modern C++ avoids raw new.