Const is a New Keyword introduced in C ++, which brings great convenience to C ++ programming. The pointer to the const object and the const pointer are two very similar concepts. They are very easy to confuse for beginners.
1. pointer to the const object
You can understand the pointer to the const object as follows: the pointer to the const object is a pointer and cannot be used to modify the value of the object to which it points.
Declaration method: const int * P;
The const object cannot be modified after initialization. Therefore, we cannot use a normal pointer to point to a const object, that is, the following assignment will cause compilation errors:
Const int I = 1;
Int * P = & I; // Error
Otherwise, we can use a normal pointer to modify the value of a const object, so the const is meaningless.
The correct method is to use a pointer to the const object to obtain the address of the const object:
Const int I = 1;
Const int * P = & I; // correct
In this way, the value of the const object cannot be modified by using the pointer pointing to the const object.
Note the following two points:
The pointer to the const object is not of the const type (this is also the main difference between it and the const pointer), so it can point to another const object;
A pointer to a const object can be assigned a non-const object address. However, it is illegal to use this pointer to modify the object value.
2. Const pointer
const pointer can be understood as follows: const pointer is a pointer and itself is of the const type. Therefore, after initializing const, it cannot be changed, that is, it cannot point to a new object
declaration method:
int * const P; // point to the const pointer of a non-const object
const int * constp; // The const pointer to the const object
as shown in the preceding Declaration method, the const pointer can point to the const object and non-const object, but the Declaration methods are different.
you cannot use the const pointer to modify its address value. However, if the const Pointer Points to a non-const object, you can use it to modify the value of the object to which it points.