c 常量 const

来源:互联网 发布:linux 复制文件夹 编辑:程序博客网 时间:2024/04/30 19:39



1、const定义的值是不可以改变的,类似于java的final

#include  "stdio.h"  main(){    int const x = 15;    x = 16;    printf("%d\n",x);}

输出:

pateo@pateo-B86N53X:~/work/study$ cc main.c -o mainmain.c: In function ‘main’:main.c:6: error: assignment of read-only variable ‘x’

2、指针常量

#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和指针的关系了

原创粉丝点击