C语言----const的用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41026740/article/details/79736024

关于const的用法做以下总结:
1、定义常变量

const int a = 10;

	int a = 10; // 可读可写
	int b = a;  //a做右值
	a = 100;  //a做左值
	//左值:放在赋值“=”符号左边,左值用写权限
	const int ca = 100; // 只读变量(不能写,不能做左值)
	ca = 200;   //error,ca不可做左值
	const int cb; //error,cb为随机值,不能改,无意义
	ca = 100; //error,虽然ca赋的值与const里的相同,仍为错误

2、数据类型对于const是透明的,即const int等同于int const
const int ca = 10;等同于int const ca = 10;

3、const直接修饰的内容不能做左值

const int *cp = &a;
cp1 = &b; //ok
*cp1 = 20; //error
int 对const是透明的,去掉int,const修饰*cp1,所以cp1不能做左值
int *const cp3 = &a;  //const修饰cp3
cp3 = &b;   //error
*cp3 = 100;  //ok
int const * const cp4 = &a;
cp4 = &b;   // error
*cp4 = 40;  //error


4、权限的传递
权限的同等或者缩小传递合法,放大传递非法。
int const *cp1 = &a;
cp1 = &ca; //cp1不许解引用
int *const cp3 = &ca;  //error,cp3可解引用
const char *p;  //不允许p解引用,防止修改源的值

猜你喜欢

转载自blog.csdn.net/qq_41026740/article/details/79736024