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, you cannot use it 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 a compilation error:
const int I = 1;
I Nt * 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 to which it points cannot be modified by using the pointer to the const object.
Note:
the pointer to the const object is not of the const type itself (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, the operation that attempts to use this pointer to modify the object value is illegal
2. Const pointer
The const pointer can be understood as follows:A const pointer is a pointer and itself is a const type.So after initializing it, you cannot change its direction, that is, you cannot point it to a new object.
Declaration method:
Int * const P; // The const pointer to a non-const object
Const int * constp; // const pointer to the const object
From the above declaration method, we can see that the const pointer can point to the const object and non-const object, but the Declaration methods of the two 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.