const char*, char const*, char*const的区别问题几乎是C++面试中每次都会有的题目。
事实上这个概念谁都有,只是三种声明方式非常相似很容易记混。
Bjarne在他的The C++ Programming Language里面给出过一个助记的方法:
把一个声明从右向左读。
char * const cp; ( * 读成 pointer to )
cp is a const pointer to char
const char * p;
p is a pointer to const char;
char const * p;
同上因为C++里面没有const*的运算符,所以const只能属于前面的类型。
C++标准规定,const关键字放在类型或变量名之前等价的。
关于char **p 、const char **p的类型相容性问题
1。问题
char *p1;const *p2=p1;//合法
char **p1;const char**p2=p1;//不合法,会有警告warning: initialization from incompatible pointer type
char **p1;char const**p2=p1;//不合法,会有警告warning: initialization from incompatible pointer type
char**p1;char*const*p2=p1;//合法
2。判断规则
明确const修饰的对象!对于指针p1,和p2,若要使得p2=p1成立,则可读做 :
“p1是指向X类型的指 针,p2是指向“带有const限定”的X类型的指针 “。
char *p1;const char *p2=p1;//合法:p1是指向(char)类型的指针,p2是指向“带有const限定"的(char)类型的指针。
char **p1;const char**p2=p1;//不合法:p1是指向(char*)类型的指针,p2是指向 ((const char)*)类型的指针。
char **p1;char const**p2=p1;//不合法;与上等价。
char**p1;char*const*p2=p1;//合法: p1是指向(char *)类型的指针,p2是指向“带有const限定"的(char*)类型的指针。
最后上一个例子:
#include <stdio.h>
int main(void){
int v1 = 1;
int v2 = 2;
int const *a = &v1;
*a = 2;
int *const b = &v2;
b = &v1;
char**p1;
char*const*p2=p1;
*p2 = &v1;
return 0;
}
编译时出现如下错误:
const.c: In function 'main':
const.c:9: error: assignment of read-only location '*a'
const.c:12: error: assignment of read-only variable 'b'
const.c:16: error: assignment of read-only location '*p2'