Let’s first define three variables
1、const int *p1
2、int const *p2
3、int *const p3
The three pointers P1, P2 and P3 all point to int type. What’s the difference between them
Write a code to test it
Compile it
You can see the error reported on lines 11, 12 and 16, from which you can draw the following conclusions:
Const int * has the same effect as int const *. The memory pointed to cannot be changed, that is, the content pointed to by the pointer is read-only, or a constant. However, the pointing position can be changed, that is, P1 and P2 can point to other constants again.
On the contrary, char * const indicates that the content of the pointer is read-only, that is, the position pointed to by the pointer cannot be modified, but the memory pointed to by the pointer is readable and writable.
What if the memory and location pointed to cannot be changed?
Hahaha, I’m sure you can think of it,
Int * const const pointer and const int * const pointer are OK.
What if const and typedef were used together?
//Define a new type first
typedef int *intp;
const intp p1;
intp const p2;
P1 and P2, which pointing position cannot be changed and which pointing memory cannot be changed?
The answer is: P1 and P2 are the same. The pointing position cannot be changed, that is, if you point to a, you can no longer point to B.
Therefore, if the content you want to point to cannot be changed, you can’t use typedef to define a new type.
Here are the validation code and compilation results
summary
The above is the combination of C language keyword const and pointer introduced by Xiaobian. I hope it will be helpful to you!