关键字const 4 大作用
#include<stdio.h>
//3.const作为修饰参数,表示该参数不能能被修改
void mystrcpy(char*dest,const char*src)
{
while((*dest++=*src++)!='\0');
}
//4.const修饰函数返回值,表示返回值不允许修改
int main()
{
//1.修辞只读变量,不能通过变量本身修改变量的值
//可以通过其他方式改变只读变量
const int a=2;
//a++;//不能通过变量本身修改变量值
int *p=(int*)&a;
*p=3;
printf("%d\n",a);
//2.const 满足就近原则
int num=10;
int const *b=#//const修饰的是*b (*b表示取值)int const *b等价于 const int *b表示不能修改b指向的地址的内容,可以
修改指向的地址
//*b=11;
printf("%p\n",b);
b++;
printf("%p\n",b);
printf("num is %d\n",num);
int num1=11;
int *const c=&num1;//const 修饰的是指针c,即变量c指向的地址不能改变,指向的地址的内容可以改变
*c=13;
printf("num1 is %d\n",num1);
//c++ ;//报错:error: increment of read-only variable ‘c’
int num2=15;
const int *const d=&num2;//表示指针指向的地址的内容不允许修改,并且指针本身也不能修改,即指向的地址也不能修改
//*d=16;
//d++;
printf("%d\n",num2);
char ch1[]="hello";
char *ch2="world";
mystrcpy(ch1,ch2);
printf("ch1 is %s",ch1);
return 0;
}
注意:const遵循就近原则
1)int const *a等价与const int *a表示指针指向的地址的内容不允许修改即
不允许:*a=11;
允许:a++;
2)int *const a 表示const修饰的是指针,即指针本身不允许修改,可以修改指针指向的地址的内容
不允许:a++
允许:*a=11
关键字const
最新推荐文章于 2024-01-04 10:30:50 发布