如题,这三者的区别和含义是?
stackoverflow上有一模一样的问题,我就复制粘贴了
Read it backwards (as driven by Clockwise/Spiral Rule):
int* - pointer to int
int const * - pointer to const int
int * const - const pointer to int
int const * const - const pointer to const int
Now the first const can be on either side of the type so:const int == int const
const int const == int const const
If you want to go really crazy you can do things like this:int ** - pointer to pointer to int
int ** const - a const pointer to a pointer to an int
int const - a pointer to a const pointer to an int
int const ** - a pointer to a pointer to a const int
int const const - a const pointer to a const pointer to an int
// const 修饰的是 p0
char *const p0; // p0 是常量,不可修改。*p0 是变量,可修改。
// const 修饰的是 *p1 和 *p2
const char *p1; // p1 是变量,可修改。*p1 是常量,不可修改。
char const *p2; // 同上。
// 第一个 const 修饰的是 *p3
// 第二个 const 修饰的是 p3
const char *const p3; // p3 和 *p3 都是常量,不可修改。
char const *const p4; // 同上。
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
在阅读和const相关的指针时,可以记一下这个规则:
左数右指
。意思是:当const出现在
*
号左侧时,指针指向的数据不可改变;当const出现在*
号右侧时,指针指向不可改变(不可改变的意思是不能通过当前指针直接进行改变)。