1、const定義的值是不可以改變的,類似於java的final
[html]
#include "stdio.h"
main(){
int const x = 15;
x = 16;
printf("%d\n",x);
}
輸出:
[html]
pateo@pateo-B86N53X:~/work/study$ cc main.c -o main
main.c: In function ‘main’:
main.c:6: error: assignment of read-only variable ‘x’
2、指針常量
[html]
#include "stdio.h"
main(){
int a=3;
int b=6;
int c=9;
int const *p=&a;
int *const p1=&b;
int const *const p2=&c;
p=&b;
//*p=4;/** 報錯,error: assignment of read-only location ‘*p’ **/
a=4;
// p1=&a;/** 報錯,error: assignment of read-only location ‘p1’ **/
*p1=5;
b = 7;
p2=&c;/** 報錯,error: assignment of read-only location ‘p2’ **/
*p2=8;/** 報錯,error: assignment of read-only location ‘*p2’ **/
c = 3;
}
總結:特別是從指針常量的列子中我們基本上能明白const和指針的關系了