您的位置:首页 > 其它

"typedef char * pc; const pc a;“ 为什么是a而不是a所指向的字符为const

2015-10-16 14:20 417 查看
问:声明如下:

typedefchar * pc;

constpc a;

为什么是a而不是a所指向的字符为const?

答:typedef的替换并不是简单的替换,在声明中,

constpc a;

a被声明为const的原因跟const inti中的i被声明成const的原因一样,a的声明不会“深入”typedef的内容来发现涉及了指针。

验证代码:

1 #include <stdio.h>

2

3 typedef char * pc;

4

5 int main(){

6 const pc a;

7 char b = 'A';

8 a=&b;//note

9 *a=b;

10 printf("*a = %c, b =%c\n", *a, b);

11 return 1;

12 }

编译报错信息如下:

zzl@SOFT30-46:~/test/test_const$ gcc -gtest_const_typedef.c -o test_const_typedef

test_const_typedef.c: In function ‘main’:

test_const_typedef.c:8:2: error: assignment of read-only variable ‘a’

结束
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: