網頁

2017年9月1日 星期五

[C++] constant of pointer

身為一個專業的C/C++工程師如果不懂 constant of pointer 真的就太鳥了。

各位大神肯定了解,就容小弟整理出來。

If I write,

char     *const *const *const test1 = ppstr;

only ***test1 can be modified.

so,

char           *const *const *const test1 = ppstr;
char  const *         *const *const test2 = ppstr;
char  const *const *         *const test3 = ppstr;
char  const *const *const *         test4 = ppstr;

***test1 = NULL; //OK
**test2 = NULL; //OK
*test3 = NULL; //OK
test4 = NULL; //OK

//**test1 = NULL; //compile error
...

The method is viewing from right to left, and see if any const in the lefthand of to modified obj, if there is, this obj can not be modified or compile error.

e.g.
char  const *const *const *         test4 = ppstr;
                 ^4       ^3      ^2       ^1
// test4 can be modified, due to there is no 'const' in the lefthand of ^1.
// This also means test4 is pointer of pointer of pointer of char which can be modified