# const, volatile and qualifiers

> A cv-qualifier attaches to one level of a type, and whether it is top-level or buried inside a pointer decides what it protects, what is ignored, and which conversions are safe. const promises nothing about pointees, modifying a const object is undefined, and volatile is about observable accesses, not threads.

- **Source:** C++ Atlas (https://cppatlas.com/topics/const-volatile-and-qualifiers)
- **Track:** Types and initialization
- **Estimated reading time:** 13 minutes
- **ISO C++ clauses:** [basic.type.qualifier] (https://eel.is/c++draft/basic.type.qualifier), [dcl.type.cv] (https://eel.is/c++draft/dcl.type.cv), [conv.qual] (https://eel.is/c++draft/conv.qual), [dcl.fct] (https://eel.is/c++draft/dcl.fct), [class.this] (https://eel.is/c++draft/class.this), [class.mfct.non.static] (https://eel.is/c++draft/class.mfct.non.static), [dcl.stc] (https://eel.is/c++draft/dcl.stc), [class.ctor.general] (https://eel.is/c++draft/class.ctor.general), [intro.abstract] (https://eel.is/c++draft/intro.abstract), [expr.ass] (https://eel.is/c++draft/expr.ass), [depr.volatile.type] (https://eel.is/c++draft/depr.volatile.type), [dcl.constexpr] (https://eel.is/c++draft/dcl.constexpr), [res.on.data.races] (https://eel.is/c++draft/res.on.data.races)
- **cppreference links:** [cv (const and volatile) type qualifiers](https://en.cppreference.com/w/cpp/language/cv), [Non-static member functions (const- and ref-qualified)](https://en.cppreference.com/w/cpp/language/member_functions), [Implicit conversions (qualification conversions)](https://en.cppreference.com/w/cpp/language/implicit_conversion), [constexpr specifier](https://en.cppreference.com/w/cpp/language/constexpr), [std::as_const](https://en.cppreference.com/w/cpp/utility/as_const)
- **Prerequisites:** implicit-conversions, value-categories

## The one idea

`const` and `volatile` are **cv-qualifiers**, and each one qualifies exactly one level of a type. In `const int* p`, the `int` is const and the pointer is not. In `int* const p`, the pointer is const and the `int` is not. Almost every rule about qualifiers depends on which level you are talking about.

A qualifier on the outermost level, the object itself, is **top-level**. It controls whether that object may be modified, and it is dropped whenever only the value matters: when copying, when deducing `auto`, and in function parameter types. A qualifier on a deeper level, such as what a pointer points to, is **low-level** and is part of the type in every context, because it protects someone else's object.

> **Mental model.** Read a declaration from the name outward, right to left: `int const* const p` is "p is a const pointer to const int". Every `const` you meet guards exactly the thing immediately to its left, or the thing to its right if nothing is on its left.

## Where qualifiers attach and where they vanish

Every non-function, non-reference type `T` has four versions: `T`, `const T`, `volatile T` and `const volatile T`. References and function types cannot be cv-qualified; if a typedef or `decltype` makes it look as if they are, the qualifier is silently ignored. Arrays are the odd case: a qualifier applied to an array type attaches to its elements, and the array type is then considered to have the same qualification, so `std::is_const_v<const int[3]>` is true.

Top-level qualifiers disappear in several places:

- **Parameters.** [dcl.fct] removes top-level cv-qualifiers when forming a function's type, so `void f(int)` and `void f(const int)` declare the same function. Inside the definition, the parameter is still const.
- **Prvalues.** A prvalue of non-class type is never cv-qualified, so a function returning `const int` really returns an `int`.
- **Deduction.** `auto x = ci;` with a `const int ci` deduces `int`, while `auto& r = ci;` deduces `const int&`; the type-deduction-auto-decltype topic has the full rules.

```cpp
void f(int);
void f(const int);         // redeclares f(int)
void f(int*);
void f(const int*);        // a different function: low-level const
void f(int* const);        // redeclares f(int*)

void f(const int x) {      // defines f(int); x is const in here
  // x = 1;                // ill-formed
  (void)x;
}
```

A default-initialized const object of class type needs a user-provided default constructor or a default member initializer for every member, so `struct W { int a; }; const W w;` is ill-formed while `struct W { int a = 0; };` is fine. A const variable at namespace scope that is not `inline`, `extern` or `volatile` has internal linkage, which the translation-units-and-linkage topic explains.

## Qualification conversions across pointer levels

The qualification conversion ([conv.qual]) adds cv-qualifiers below the top level. Adding `const` one level down is always safe: `int*` converts to `const int*`. Two levels down, the obvious conversion is banned.

```cpp
const int secret = 42;

void attack() {
  int* p = nullptr;
  // const int** pp = &p;   // ill-formed. If it were allowed:
  // *pp = &secret;         // fine: storing a const int* through const int**
  // *p = 0;                // p now points to secret: writes a const object
  int* const* ok1 = &p;          // OK
  const int* const* ok2 = &p;    // OK: the middle level is const too
  (void)ok1; (void)ok2;
}
```

```text
  int**           ->  const int**          banned: middle level still writable
  int**           ->  const int* const*    allowed: every level above is const
  int**           ->  int* const*          allowed: const only one level down
  level:   0  1  2        (0 is the outermost pointer)
```

The rule is that if a qualifier is added at some level, `const` must also be added at every level between it and the top, excluding the top level itself. Otherwise the intermediate pointer remains writable, and you could store a pointer to a const object into a slot that the original type sees as pointing to non-const.
> **Standardese.** [conv.qual] describes the rule through cv-decompositions of similar types. Since C++20 (P0388) the same machinery also lets an array of known bound convert to an array of unknown bound inside a pointer, so `int(*)[3]` converts to `const int(*)[]`.

## Const objects and undefined modification

[basic.type.qualifier] defines a **const object** as an object of const-qualified type or a non-mutable subobject of one. [dcl.type.cv] makes any attempt to modify a const object during its lifetime undefined behavior. The implementation may place such objects in read-only memory, fold their values into code, or assume they never change across function calls.

Constness belongs to the object, not to the path. Reaching a non-const object through a `const int&` and casting the const away to write is allowed; reaching a const object through any path and writing is undefined. The casts topic shows `const_cast` in both situations.

Constructors and destructors are the exception built into the rule. [class.ctor.general] says const and volatile semantics do not apply to an object under construction; they take effect when the most derived object's constructor finishes and end when its destructor starts. That is why a constructor can assign to members of an object declared `const`.

## const member functions, mutable and logical const

A non-static member function declared `const` gets `this` of type `const X*` ([class.this]), so inside it every non-static data member is accessed as const. A const member function is the only kind that can be called on a const object or through a `const X&`, and you can overload on it, which is how `operator[]` returns `const T&` for const containers and `T&` otherwise.

That const is **bitwise and shallow**. It applies to the members themselves, not to what pointer members point to. A const member function may modify the pointee of a raw pointer or `std::unique_ptr` member. The Library Fundamentals TS offers `std::experimental::propagate_const` to make constness reach through such members.

```cpp
#include <memory>

struct Buffer {
  int* raw;
  std::unique_ptr<int> owned;
  void clear() const {
    raw[0] = 0;   // OK: raw is int* const here, the int is not const
    *owned = 0;   // OK for the same reason
    // raw = nullptr;  // ill-formed: the member itself is const
  }
};
```

**Logical const** is the opposite design: the object's observable state does not change, even if some bits do. The `mutable` specifier ([dcl.stc]) marks a data member that may be modified through a const object, which is how caches, lazily computed values and mutexes live inside const member functions. `mutable` cannot be applied to a reference, a static member or a const member.

```cpp
#include <mutex>
#include <string>

class Name {
  std::string first_, last_;
  mutable std::mutex m_;
  mutable std::string full_;  // cache: logically part of the value
public:
  const std::string& full() const {
    std::lock_guard lock(m_);
    if (full_.empty()) full_ = first_ + " " + last_;
    return full_;
  }
};
```

> **Pitfall.** [res.on.data.races] promises that standard library functions do not modify objects reached only through const arguments, so callers reasonably treat const operations as safe to run concurrently. A `mutable` cache without a mutex or an atomic breaks that assumption and turns two concurrent const calls into a data race.

## volatile: observable accesses, not threads

[intro.abstract] makes every access through a volatile glvalue part of the program's observable behavior. The compiler must perform each such read and write, in program order relative to other volatile accesses, and may not merge, remove or invent them. This is for memory-mapped hardware registers, for locals that must survive `longjmp`, and for `volatile std::sig_atomic_t` flags shared with a signal handler.

`volatile` gives no atomicity and no ordering with respect to other threads. Two threads accessing a `volatile int` without synchronization, where at least one writes, is a data race and undefined; use `std::atomic`, which the atomics-and-memory-ordering topic covers.

C++20 adopted P1152 and deprecated uses of `volatile` whose meaning was unclear:

- `++` and `--` on a volatile object, which read and write but look like one access;
- using the value of a simple assignment to a volatile object, as in `a = v = 1`;
- volatile-qualified function parameters and return types;
- volatile structured bindings.

P1152 also deprecated compound assignment such as `v += 1`. P2327 restored the bitwise forms, and CWG 2654, resolved for C++23 and treated as a defect against C++20, restored all of them, so compound assignment on a volatile is not deprecated.

```cpp
volatile int reg;

void poke() {
  reg = 1;       // OK: assignment used as a statement
  reg += 2;      // OK: not deprecated since CWG 2654
  reg |= 4;      // OK
  // ++reg;      // deprecated since C++20
  // int x = (reg = 5);   // deprecated: value of a volatile assignment is used
}
```

## constexpr versus const

`const` means "this object will not be modified". `constexpr` on a variable means "this object is initialized by a constant expression and is usable in constant expressions", and it implies `const`. A `const` variable may be initialized at run time, so `const int n = read();` is const but cannot size an array.

There is an old shortcut: a const variable of integral or enumeration type initialized with a constant expression is usable in constant expressions without `constexpr`. The shortcut does not extend to floating types, so `const double d = 1.0;` cannot initialize a `constexpr double`.

`constexpr` is always top-level. `constexpr int* p = &g;` declares `p` as `int* const`, so `*p = 5` is fine, and `g` must have static storage duration for its address to be a constant expression. To make the pointee const you still write `constexpr const int* p`.

```cpp
#include <type_traits>

int g = 0;
constexpr int* p = &g;
static_assert(std::is_same_v<decltype(p), int* const>);
void set() { *p = 5; }   // OK: the pointee is not const

const int n = 4;
int arr[n];              // OK: const integral with a constant initializer
// const double d = 1.0;
// constexpr double e = d;  // ill-formed: d is not usable in constant expressions
```

For member functions the link was cut in C++14: a `constexpr` non-static member function is no longer implicitly `const`, so calling one on a const object needs an explicit `const`. Constant evaluation in depth is the constant-expressions topic's subject.

## What to remember

- Each qualifier applies to one level; top-level const protects the object, low-level const protects what it points to.
- Top-level cv is dropped in parameter types, on non-class prvalues and in `auto` deduction by value.
- `T**` does not convert to `const T**`; `const T* const*` is fine, because every intermediate level must be const.
- Modifying a const object is undefined, however you reach it; constructors and destructors are exempt.
- const member functions make members const, not pointees; `mutable` allows logical const and needs synchronization.
- `volatile` makes accesses observable but is not atomic; C++20 deprecated `++`, `--`, volatile parameters and using a volatile assignment's value, while compound assignment was restored.
- `constexpr` implies top-level const; const integral variables with constant initializers are usable in constant expressions, const doubles are not.
- Since C++14, `constexpr` member functions are not implicitly `const`.

## Concept Map Outline

- **const and volatile:** Each cv-qualifier applies to one level of a type; the level decides what it protects.
  - **Levels:** Top-level qualifies the object itself; low-level qualifies what it points to.
    - **Read right to left:** int const* const p is a const pointer to const int.
    - **Parameters drop top-level:** void f(int) and void f(const int) declare the same function.
    - **Prvalues drop cv:** A non-class prvalue is never cv-qualified, so returning const int returns int.
    - **Arrays and references:** cv on an array applies to its elements; cv on a reference or function type is ignored.
  - **Qualification conversion:** Adds cv below the top level of a pointer type.
    - **T** to const T**:** Banned: the writable middle pointer could be made to point at a const object.
    - **const T* const*:** Allowed: if a level gains const, every level above it except the top must be const.
    - **Unknown bounds (C++20):** P0388 lets int(*)[3] convert to const int(*)[].
  - **Const objects:** Objects created const, or non-mutable subobjects of them.
    - **Modification is UB:** Writing a const object is undefined, whatever path or cast reaches it.
    - **Path is irrelevant:** A non-const object reached through const T& may be written after const_cast.
    - **Under construction:** Const semantics start when the constructor finishes and stop when the destructor starts.
  - **const member functions:** this has type const X*, so members are accessed as const.
    - **Shallow const:** Pointer members become T* const; the pointees stay modifiable.
    - **mutable:** Lets a member change in a const object; not allowed on references, statics or const members.
    - **Logical const:** Observable state is unchanged even when caches or mutexes change.
    - **Thread safety:** Callers assume concurrent const calls are safe, so a mutable cache needs a lock or atomic.
  - **volatile:** Accesses through volatile glvalues are observable behavior.
    - **Not atomic:** Unsynchronized volatile accesses from two threads are a data race; use std::atomic.
    - **C++20 deprecations:** ++ and --, using a volatile assignment's value, volatile parameters, returns and bindings.
    - **Compound assignment:** Deprecated by P1152, then restored by P2327 and CWG 2654; not deprecated in C++23.
  - **constexpr vs const:** const forbids modification; constexpr also demands constant initialization.
    - **Top-level only:** constexpr int* p is int* const; the pointee is still writable.
    - **Integral shortcut:** A const integral variable with a constant initializer is usable in constant expressions.
    - **Not for doubles:** const double d = 1.0 cannot initialize a constexpr double.
    - **Members (C++14):** A constexpr member function is no longer implicitly const.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.ptr], [basic.type.qualifier])

Which two of the commented statements would be ill-formed if uncommented?

```cpp
void demo() {
  int a = 0, b = 0;
  const int* p = &a;
  int* const q = &a;
  // *p = 1;   // (1)
  // p = &b;    // (2)
  // *q = 1;    // (3)
  // q = &b;    // (4)
  (void)p; (void)q; (void)b;
}
```

A. (1) and (3)
B. (1) and (4)
C. (2) and (3)
D. (2) and (4)

**Answer (B):** (1) and (4)

**Why:** In `const int* p` the `const` qualifies the `int`, so the pointee cannot be written through `p` but `p` itself can be reseated: (1) fails, (2) is fine. In `int* const q` the `const` qualifies the pointer, so `q` cannot be reseated but the `int` can be written: (3) is fine, (4) fails. Reading each declaration right to left from the name gives the answer directly.

### Question 2 [warmup] ([dcl.stc], [basic.type.qualifier], [dcl.type.cv])

What does this program print?

```cpp
#include <cstdio>

struct Widget {
  mutable int reads = 0;
  int value = 42;
  int get() const { ++reads; return value; }
};

int main() {
  const Widget w;
  w.get();
  w.get();
  std::printf("%d\n", w.reads);
}
```

A. Nothing: `get` modifies the object but is `const`, so the program is ill-formed
B. Undefined behavior: `w` is a const object
C. `0`
D. `2`

**Answer (D):** `2`

**Why:** A `mutable` member is not part of the const object: [basic.type.qualifier] defines a const object's subobjects as const only when they are non-mutable. So `get` may increment `reads` even through `const Widget*`, and doing so on a const object is well-defined. The program prints `2`. Without `mutable`, the increment would be ill-formed, not undefined.

### Question 3 [warmup] ([dcl.fct], [over.load])

How many distinct functions do these declarations declare?

```cpp
void f(int);
void f(const int);
void f(int*);
void f(const int*);
void f(int* const);
```

A. 3
B. 5
C. 4
D. 2

**Answer (A):** 3

**Why:** When the function type is formed, top-level cv-qualifiers on parameter types are removed, so `f(const int)` redeclares `f(int)` and `f(int* const)` redeclares `f(int*)`. The `const` in `f(const int*)` is low-level, part of the pointee type, so that one is a distinct overload. That leaves `f(int)`, `f(int*)` and `f(const int*)`.

### Question 4 [tricky] ([conv.qual])

Which of these initializations are ill-formed?

```cpp
void demo() {
  int* p = nullptr;
  int** pp = &p;
  const int** a = pp;        // (A)
  const int* const* b = pp;  // (B)
  int* const* c = pp;        // (C)
  (void)a; (void)b; (void)c;
}
```

A. (B) only
B. (A) and (B)
C. (A) only
D. None of them

**Answer (C):** (A) only

**Why:** Adding `const` two levels down is only allowed if every level in between, except the outermost, becomes `const` as well. (A) leaves the middle pointer writable, so through `a` you could store the address of a `const int` into `p` and then modify it through `p`; the conversion is banned and (A) is ill-formed. (B) makes the middle level const, closing that hole, and (C) adds `const` only one level down, which is always safe.

### Question 5 [tricky] ([dcl.constexpr], [expr.const])

What does the standard say about this code?

```cpp
int g = 0;
constexpr int* p = &g;

void set() { *p = 5; }
```

A. Well-formed: `p` has type `int* const`, so the pointee is modifiable
B. Ill-formed: `constexpr` makes `*p` const
C. Ill-formed: a constexpr pointer cannot point to a non-const object
D. Undefined behavior: it modifies an object that a constant expression refers to

**Answer (A):** Well-formed: `p` has type `int* const`, so the pointee is modifiable

**Why:** `constexpr` on a variable implies `const` on that variable only, which is top-level. `p` is a constant pointer to a modifiable `int`, and `&g` is a constant expression because `g` has static storage duration. Writing through `p` modifies `g`, which is not a const object. To protect the pointee as well you would write `constexpr const int* p`.

### Question 6 [tricky] ([class.this], [expr.ref], [dcl.type.cv])

What does the standard say about calling `clear` on a `const Buffer` whose `data` points to a non-const `int` array?

```cpp
struct Buffer {
  int* data;
  void clear() const { data[0] = 0; }
};
```

A. Ill-formed: inside a const member function `data[0]` is const
B. Ill-formed unless `data` is declared `mutable`
C. Undefined behavior whenever it is called on a const `Buffer`
D. Well-formed and well-defined: only the pointer `data` itself is const inside `clear`

**Answer (D):** Well-formed and well-defined: only the pointer `data` itself is const inside `clear`

**Why:** In a const member function, `this` is `const Buffer*`, so the member `data` is accessed as `int* const`: the pointer is const, the pointee is not. Writing `data[0]` modifies an `int` that is not part of the `Buffer` object and not const, so there is no undefined behavior. This shallowness is the gap between bitwise const and logical const.

### Question 7 [standardese] ([expr.pre.incr], [expr.ass], [depr.volatile.type])

Given `volatile int v;` at namespace scope, which statement inside a function is deprecated in C++23?

A. `v += 1;`
B. `++v;`
C. `v |= 1;`
D. `int x = v;`

**Answer (B):** `++v;`

**Why:** C++20 (P1152) deprecated increment and decrement of volatile objects, and that deprecation remains in C++23. P1152 also deprecated compound assignment, but P2327 restored the bitwise forms and CWG 2654 restored the rest, so `v += 1` is not deprecated in C++23; GCC 16 and Clang 21 warn only about `++v`. Reading a volatile object is the plain, intended use.

### Question 8 [standardese] ([dcl.constexpr], [class.mfct.non.static], [over.match.funcs])

In C++23, what does the standard say about this code?

```cpp
struct S {
  int v;
  constexpr int get() { return v; }
};

constexpr S s{1};
static_assert(s.get() == 1);
```

A. Well-formed: constexpr member functions are implicitly `const`
B. Well-formed: `s` is constexpr, so `get` is evaluated at compile time regardless
C. Ill-formed: `get` is not a const member function and `s` is const
D. Ill-formed: `S` needs a constexpr constructor to be used in a constexpr variable

**Answer (C):** Ill-formed: `get` is not a const member function and `s` is const

**Why:** A `constexpr` variable is implicitly `const`, so `s.get()` needs a const member function. In C++11 a constexpr non-static member function was implicitly const, which is the tempting first option, but C++14 removed that rule, so `get` here is a non-const function and cannot be called on `s`. `S` is an aggregate, so it needs no constructor for `s{1}`.
