CKTIS / C++
Pointer declarator (*) in C++
Learn how ISO C++23 uses `*` to declare pointers, where to put `const`, and how to distinguish a pointer to an array from an array of pointers.
Version: ISO C++23; implementation support may vary
Syntax
T* p = nullptr;
T const* read = &obj;
T* const fixed = &obj;
T const* const fixed_read = &obj;
T** pp = &p;
T* slots[N];
T (*whole)[N] = &array;
R (*fn)(Args...);The pointer declarator (*) adds a pointer level to a type. In int* p, q;, the star belongs to the declarator for p alone; q is an int. Spacing does not change this. int** pp is a pointer to a pointer. In expressions, built-in & in &x takes the address of x, and built-in unary * in *p dereferences the pointer; it is neither a declaration nor multiplication. In int& r = x;, & declares an lvalue reference instead of taking an address.
const int* p (equivalently int const* p) lets you reassign p, but not modify the pointed-to int through p. int* const p fixes the pointer value after initialization but allows you to modify the pointed-to int. const int* const p combines both restrictions. By-value parameters of type int* and const int* can distinguish overloads; int* and int* const cannot.
int* a[3] is an array of three pointers, but int (*a)[3] is a pointer to a whole array of three int elements. Similarly, int (*f)(double) is a function pointer, whereas int* f(double) declares a function that returns a pointer. int C::* m declares a distinct type: a pointer to a non-static data member of C.
A raw pointer does not by itself express ownership or extend an object's lifetime. An array can convert to a pointer to its first element; that pointer does not carry the length. If a pointer should not point to an object yet, initialize it to nullptr rather than leaving a local pointer uninitialized. A non-null check does not establish that the object is alive or that an index is in bounds. Dereferencing a null or one-past-the-end pointer, or accessing an object through a dangling pointer, causes undefined behavior.
Examples
#include <iostream>
int main() {
int values[3]{2, 4, 6};
const int* read = values;
int* const first = &values[0];
int (*whole)[3] = &values;
*first = 3;
std::cout << *read << ' ' << (*whole)[2] << '\n';
}Result
3 6
`read` points to the first element without permitting writes through it. `first` points to the same element, cannot be reassigned, and writes `3` through `*first`. `whole` points to the whole array, so `(*whole)[2]` reads its third element. Expected output: `3 6`.
Related lessons
- C++ · Lesson 47 · Advanced · Version: 3
- C++ · Lesson 49 · Advanced · Version: 3
- C++ · Lesson 51 · Advanced · Version: 3
- C++ · Lesson 56 · Advanced · Version: 3
- C++ · Lesson 58 · Advanced · Version: 3