您的位置:首页 > 其它

const 的主要用法

2011-03-28 20:33 176 查看
const 主要是为了增强程序的健壮性,减少程序少出错。

const 修饰的值是常量,在C语言中更精确的说是只读的变量,在编译时是不能改变的。

编译器通常不为普通const 只读变量分配存储空间

const int M=1; //此时并未将m 放入内存中

const int a=100;

同时也可以这样修饰int const a=100;

 

修饰数组
定义或说明一个只读数组可采用如下格式:
int const a[5]={1, 2, 3, 4, 5};或
const int a[5]={1, 2, 3, 4, 5};

对指针的修饰

const int *p;//p可变,p所指向的内容不可变

int const *p;//p可变,p所指向的内容不可变

int *const p;//P不可变,p所指向的内容可变

const int *const p;//p和p所指向的内容均不可变

const 也可以修饰函数参数,主要是为了防止函数体内对参数意外的改变。比如int FUN(const int i);

const 修饰符也可以修饰函数的返回值,返回值不可被改变

如:const int Fun (void)

下面举个例子啊!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  fun 编译器 语言 存储 c