const的使用

const的使用

作用:定义常变量,不允许修改其值,例如:int const ca = 10 ;

int const ca = 10 ;
ca = 20 ; //error
int const cb ; //error
int a = 10 ;
a = 20 ; //ture

规则:1、数据基本的数据类型对于const是透明的。int const ca = 0 ;
const int cb = 0 ; ca和cb 是等价的。
2、const 限定它的直接右边

const int *cp = &a ;
*cp = 100 ;//error,const限定*,*是const的直接右边
const int *cp = &a ;
cp = &b ;//ture
int *const cp2 = &a ;
cp2 = &b;//error,直接右边不能做左值
const int *const cp3 = &a;
cp3 = &b; //error
*cp3 = 100 ; //error

3、权限可以缩小,不能发大

int main()
{
	int a = 10;
	int b = 20;
	const int ca = 10;
	const int cb = 20;
	int *p1 = &a;
	//int *p2 = &ca;//error
	const int *p3 = &a;
	const int *p4 = &ca;
	int *const p5 = &a;
	//int *const p6 = &ca;//error

	return 0;

strlen,sizeof的使用

strlen(str): 求字符串str的有效长度,不包含\0
sizeof(a):求a的字节数

int main()
{
	char str1[100] = "abcde";
	char str2[] = "abcde";
	char str3[100] = "abcdef\n\0ghi";
	char str4[] = "abcdef\n\0ghi";//数组不管\0
	char *str5 = "abcde";
	char *str6 = "abcdef\n\0ghi";
	printf("%d,%d\n",strlen(str1),sizeof(str1));//5,100*1
	printf("%d,%d\n",strlen(str2),sizeof(str2));//5,6*1
	printf("%d,%d\n",strlen(str3),sizeof(str3));//7,100
	printf("%d,%d\n",strlen(str4),sizeof(str4));//7,12
	printf("%d,%d\n",strlen(str5),sizeof(str5));//5,4
	printf("%d,%d\n",strlen(str6),sizeof(str6));//7,4
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值