In C++, there are three distinct concepts involving const and pointers that are often confused: pointer to constant (常量指针), constant pointer (指针常量), and constant pointer to constant (const修饰的指针常量). Understanding the differences between these is essential for writing safe and correct C++ code.
Key Differences
Pointer to Constant (常量指针): This is a pointer that points to a constant value. The pointer can be reassigned to point to different objects, but the value at the pointed-to location cannot be modified through this pointer.
Constant Pointer (指针常量): This is a constant pointer. The pointer itself cannot be reasssigned to point to a different adress after initialization. However, the value stored at the address it points to can be modified.
Constant Pointer to Constant (const修饰的指针常量): This pointer cannot be reassigned to point elsewhere, and the value at the pointed-to location cannot be modified through this pointer. Both the pointer and the data are immutable.
Initialization Requirements
One important distinction is in initialization:
- Pointer to constant: Does not require initialization at declaration
- Constant pointer: Must be initialized at declaration
- Constant pointer to constant: Must be initialized at declaration
Top-Level vs Bottom-Level Const in C++
From a compiler perspective, const qualification can be categorized as:
- Top-level const: The pointer itself is constant (applies to the pointer variable itself)
- Bottom-level const: The pointed-to value is constant (applies to what the pointer points to)
Understanding this distinction helps in predicting what operations are permitted in different contexts.
</div>Assignment Compatibility Rules
------------------------------
The assignment of pointers to `const` variables follows specific rules:
<div>```
1 const int value = 42;
2
3 const int* p1 = &value; // Valid: pointer to constant can point to const
4 int* const p2 = &value; // Error: cannot initialize int* const with const int*
5 const int* const p3 = &value; // Valid: constant pointer to constant
</div>**Output:**
<div>```
ptrX address: 0x7fff5fbff8bc
ptrX value: 100
ptrY address: 0x7fff5fbff8bc
ptrY value: 100