设为首页 加入收藏

TOP

c 常量 const
2014-11-23 23:36:30 来源: 作者: 【 】 浏览:3
Tags:常量 const


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

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C函数大全--去除了不经常使用的。 下一篇 c语言解码GPS--实现篇

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: