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