- 修饰变量为只读
pi@raspberrypi:~/study_c $ cat const.c
#include <stdio.h>
int main()
{
const int a = 10;
a = 5;
printf("a=%d",a);
return 0;
}
pi@raspberrypi:~/study_c $ ls
const.c hello.c main.c main.o mem MemTest.c
pi@raspberrypi:~/study_c $
pi@raspberrypi:~/study_c $
pi@raspberrypi:~/study_c $
pi@raspberrypi:~/study_c $
pi@raspberrypi:~/study_c $
pi@raspberrypi:~/study_c $ gcc const.c -o const
const.c: In function ‘main’:
const.c:7:4: error: assignment of read-only variable ‘a’
a = 5;
^
pi@raspberrypi:~/study_c $
2.修饰指针
- 把*读作“指针指向”,或直接读“指向”;
- 把const读作“常量”;
- 类型部分从右到左读。
int i = 0; // i是整型
const int c = 0; // c是整型常量
const int* p1 = &c; // p1是指针指向整型常量
int* const p2 = &i; // p2是常量指针指向整型
const int* const p3 = &i; // p3是常量指针指向整型常量
int const * const p4 = p3; // p4是常量指针指向常量整形(和p3一样)
网友评论