作者:聂勇      欢迎转载,请保留作者信息并说明文章来源!
const关键字在C语言中有点名不符实,用它修饰变量结果不是常量而是只读常量,#define定义的才是常量。可参考我的另外一篇文章《C - 编译错误:’XXX’的存储大小不是常量》
const 修饰变量与数组
1、const 修饰变量。
为只读变量,如果修改在编译时会报错。
| 1 2 3 4 5 6 7 8 9 10
 | #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) {     const int x = 1;     x = 99;             return EXIT_SUCCESS; }
 | 
2、const 修饰数组。
为只读数组,如果修改在编译时会报错。
| 1 2 3 4 5 6 7 8 9 10
 | #include <stdio.h> #include <stdlib.h>  int main(int argc, char *argv[])  {     const int arr[] = {1, 2, 3};     arr[0] = 99;             return EXIT_SUCCESS; }
 | 
const 修饰指针
1、常量指针。
指针指向的内容不可修改,指针可修改。定义常量指针的方式有:
| 1 2
 | int const *p = 9; const int *p = 9;
 | 
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 | #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) {     int x = 10-;     const int *p = &x;     printf("*p=%d\n", *p);             x = 11;        printf("*p=%d\n", *p);          int y = 13;     p = &y;        printf("*p=%d\n", *p);               *p = 12;        printf("*p=%d\n", *p);          return EXIT_SUCCESS }
 | 
2、指针常量。
指针指向的内容可修改,指针不可修改。定义常量指针的方式有:
| 1 2
 | int *const p = 9; int* const p = 9;
 | 
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 | #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) {     int x = 10;     int *const p = &x;     printf("*p=%d\n", *p);               *p = 12;        printf("*p=%d\n", *p);          int y = 13;     p = &y;        printf("*p=%d\n", *p);          return EXIT_SUCCESS; }
 | 
3、常量指针+指针常量。
指针与指针指向的内容都不可修改。定义的方式有:
| 1 2 3 4
 | const int *const p = 9; const int* const p = 9; int const *const p = 9; int const* const p = 9;
 |