typedef char *pstring;
const pstring cstr = 0; //char *const cstr
const pstring *ps; //char *const *ps
注释里的代码是否等价于注释前的代码?
1. 即const pstring cstr = 0;
等价于char *const cstr = 0;
?
2.如果是的话,那这样写pstring const cstr = 0;
岂不是更容易理解吗?
3.const pstring cstr = 0;
和pstring const cstr = 0;
是一样的意思,我说的对吗?
求助,先行谢过!
是的。
是的,我觉得书上如此举例,是为了故意制造混淆看你能否火眼金睛。
对。
说一下里面涉及的概念。
typedef char *pstring;
const pstring cstr = 0; //char *const cstr
cstr
is a constant pointer to char
. (注意,const
修饰的是 pointer.)
const char *
vs char * const
?
const char *
is a pointer to aconst char
.char * const
is a constant pointer tochar
.char * const
<==>const pstring
const char *
<==>char const *
所以 @snailcoder 对于 const
在 * 左侧还是右侧的理解是正确的。但对于 typedef
声明的理解稍有偏差。
容我直接引用书上的解释,说的很清楚了:
The base type in these declarations is const pstring. As usual, a const that appears in the base type modifies the given type. The type of pstring is “pointer to char.” So, const pstring is a constant pointer to char—not a pointer to const char.
恰好,这也解释了你第三个疑虑,const
出现在 base type 旁边,就修饰的是 base type,在左边在右边没半点差别。(这里的 base type 是 char *
, 是个指针。)
以上。
const pstring cstr = 0;//等价于const char *cstr = 0;
const pstring *ps;//等价于const char **ps;
但是,const char *cstr
不等价于char* const cstr
,const char **ps
不等价于char* const *ps
用const修饰字符指针的规则很简单:如果const位于左侧(例如const char *cstr
),则指针指向的内容是个常量;如果const位于右侧(例如char* const cstr
),则指针本身是个常量。