天天看點

指針常量與常量指針的個人見解

看了很多資料,發現很多對于這兩者的解釋都是混淆的。不是意義的混淆,而是翻譯的混淆。目前我已經分不清中文中的指針常量和常量指針了。

不過還好,英文中這兩者還是可以厘清的。

(參考資料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,常量 -指針(指向非常量),指向的對象是非常量可以修改,但是自身是常量不可被修改。

繼續閱讀