Easy Tutorial
❮ Heap Sort Runoob Architecture ❯

Differences Between Constant References, Pointers to Constants, and Constant Pointers in C++

Classification Programming Techniques

Let's first understand some precautions about references and pointers.

A pointer itself is an object.

The type of a pointer must strictly match the object it points to.

double dval;
double *pd = &dval;      // Correct
double *pd2 = pd;        // Correct

int *pi = pd;            // Error: The type of pointer pi does not match the type of pd
pi = &dval;              // Error: Attempting to assign the address of an object of type double to a pointer of type int

There is an exception: the introduction of the const qualifier

Constant Reference

When initializing a constant reference, any expression is allowed as the initial value.

int i = 42;
const int &r1 = i;       // Correct: Allows binding a const int & to a regular int object
const int &r2 = 42;      // Correct
const int &r3 = r1 * 2;  // Correct
int &r4 = r1 * 2;        // Error

double dval = 3.14;
const int &ri = dval;    // Correct
// Equivalent to
const int temp = dval;
const int &ri = temp;

int i = 42;
int &r1 = i;
const int &r2 = i;
r1 = 0;                  // Correct
r2 = 0;                  // Error

Constant Pointer

Definition: Also known as a constant pointer, it can be understood as a pointer to a constant, that is, this is a pointer, but it points to a constant, and this constant is the value of the pointer (address), not the value pointed to by the address.

Key Points:

Code Form:

int const* p;  const int* p;

Pointer to Constant

Definition: Essentially a constant, modified by a pointer. The value of the pointer constant is the pointer itself, and since this value is a constant, it cannot be assigned.

Key Points:

Code Form:

int* const p;

Constant Pointer to Constant

Definition: A constant pointer to a constant is a constant, and the object it points to is also a constant.

Key Points:

Code Form:

const int* const p;

How to distinguish these types? A const with two is definitely a constant pointer to a constant, which is easy to understand. The main point is how to distinguish between a constant pointer and a pointer to a constant:

One way is to look at the order of * and const, for example:

int const* p;   //const * means a constant pointer
const int* p;   //const * means a constant pointer
int* const p;   //* const means a pointer to a constant

Another way is to see which one const is close to, that is, look from right to left, for example:

```cpp int const* p; //const modifies *p, meaning the content of *p

❮ Heap Sort Runoob Architecture ❯