【C语言】关于const的一些用法

//const : 定义常变量 不能写,只能读
//1、使用const之前必须先初始化
//2、类型 对 const是透明的  const int a  等价于  int const a
//3、const 用于封锁直接修饰的内容,使其为只读
//4、权力只能等同或者缩小传递,但不能放大


#include <stdio.h>
int main()
{
int a = 10;//读,写
int b = 20;//读,写
int const *ca = &a;//const int *cp = &a; 
ca = &b;//只读
//*ca = 100;//不能写  
int * const cb = &b;
//cb = &a;//不能读
*cb = 200;//只写
int const * const cc = &a;
//cc = &b;//不能读
//*cc = 100;//不能写
return 0;
}


//const的应用 字符串的复制,防止源字符串被修改
/*
#include <stdio.h>
void Mystrcpy(char * des,const char *src)
{
int i;
for (i=0 ; src[i] != '\0' ; i++ )
{
des[i] = src[i];
//src[i] = '\0';//防止被解引用,被修改
}
des[i] = '\0';
}
int main()
{
char des[10];
char src[] = "adcfg";
Mystrcpy(des,src);
printf ("%s\n%s\n",des,src);
return 0;
}
*/

猜你喜欢

转载自blog.csdn.net/weixin_41576955/article/details/79846420