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;
}