const表示为只读。
const <type> 和<type> const 完全等价
问题归结为 <type> const *p 和 <type>* const p 区别;
只需要看const 后是什么类型;
前者const 修饰的是*p,他是p所指向的内容为read-only;
而后者 const 修饰的是p, 即指针变量p本身为 read-only;
从内存的角度来看:
<type> *const p 变量p存放在read-only数据段
面试考题:
const int *p
p指向的内容不能改变。
int const *p
p指向的内容不能改变。
int *const p
p不能改变。
const int *const p
p和p指向的内容都不能改变。
const <type> 和<type> const 完全等价
问题归结为 <type> const *p 和 <type>* const p 区别;
只需要看const 后是什么类型;
前者const 修饰的是*p,他是p所指向的内容为read-only;
而后者 const 修饰的是p, 即指针变量p本身为 read-only;
从内存的角度来看:
<type> *const p 变量p存放在read-only数据段
p为指针常量,p只用于读操作, 告诉编译器,p仅用做右值;
const <type> *p 变量p存放在栈区;
p为常量指针,*p不一定为常量区,但*p只用于读操作,告诉编译器*p仅用作右值;
面试考题:
const int *p
p指向的内容不能改变。
int const *p
p指向的内容不能改变。
int *const p
p不能改变。
const int *const p
p和p指向的内容都不能改变。