const用来修饰的变量时,变量为只读变量其值不能改变,除了修饰普通变量,还可以修饰指针变量,函数形参。另外,修饰一个变量时,const int i 和int const i是等效的。即const修饰符和变量类型关键词顺序可以互换。
1.const修饰指针时。
int a=9;
int * const p0=&a;
int const *p1=&a;
const int *p2=&a;
p0++; //错误,p0是常量,值不能改变
(*p0)++; //正确,*p值可以改变
p1++; //正确,p1值可以改变
(*p1)++; //错误,(*p1)是常量,值不能改变
p2++; //正确,p2值可以改变
(*p1)++; //错误,(*p2)是常量,值不能改变
2.修饰函数形参时,形参的值在函数内不能被改变。
void fun(const int tmp)
{
tmp++; //错误,tmp前有const修饰,其值不能改变
printf("tmp=%d",tmp);
}
void fun(int tmp)
{
tmp++; //正确,tmp前无const修饰,其值可改变。
printf("tmp=%d",tmp);
}
来源:CSDN
作者:weixin_39144790
链接:https://blog.csdn.net/weixin_39144790/article/details/104449965