const的用途

const的用途

在编程时有时定义一个变量,需要限定它的值不能被改变,在整个作用域中都保持不变。

const:限定变量的权限,变成只读(不能做左值)。

           左值:写权限

           右值:读权限

int main()
{
    int a;
    a = 10;//左值,放在"="符号左边就是左值,其它情况都是右值
    int b = a;
    const int ca = 10;//限定写权限,变成只读
    b = ca;//ok
    //ca = 20;//error
    //const int cb;//error
    //ca = 10;//error
    int const cb = 20;
    //cb = 30;
    b = cb;

    return 0;
}

1、基本数据类型对于const透明。

2、const修饰它的直接右边。

      const int*p=&a;=>int const *p1=&a;

      *p1=1000;//出错,*p1不能做左值

3、权限可以同等或者缩小传递,但不能放大传递。

 

例:在求字符串长度时,是字符串长度在整个作用域的长度不被改变,可以用const对变量加以限定

#include<stdio.h>
#include <assert.h>
int Mystrlen(const char *str)
{
	assert (str!=NULL);//断言,该字符串一定不为空
	int count =0;
	while(*str!='\0')
	{
		str++;
		count ++;
	}
	return count ;
}
int main()
{
	char *str="abcd";
	printf("%d\n",Mystrlen(str));
	return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值