天天看点

指针常量与常量指针的个人见解

看了很多资料,发现很多对于这两者的解释都是混淆的。不是意义的混淆,而是翻译的混淆。目前我已经分不清中文中的指针常量和常量指针了。

不过还好,英文中这两者还是可以分清的。

(参考资料https://blog.csdn.net/weixin_41028621/article/details/89159896)。

Pointer to constant
const int *ptr;
int const *ptr;

Constant pointer to variable
int *const ptr;

constant pointer to constant
const int *const ptr;

各个含义如下:
const int * pOne;
You cannot change the value pointed by ptr, but you can change the pointer itself.
int * const pTwo;
You cannot change the pointer p, but can change the value pointed by ptr.
const int *const pThree;
You can neither change the value pointed by ptr nor the pointer ptr.
           

读的时候,我们看 const 和 * 谁在后面,然后从后面往前面读 就可以了。

比如 const int *ptr; 因为 *在后面,所以读作 Pointer to constant,指向常量的指针,指向的对象不可修改(是常量),但是自身可以被重新赋值。

比如 int * const ptr; 因为const出现在后面,所以读作 Constant pointer to variable,常量 -指针(指向非常量),指向的对象是非常量可以修改,但是自身是常量不可被修改。

继续阅读