常量指针,指针常量,及const主要应用场景"/>
const用法,常量指针,指针常量,及const主要应用场景
目录
1.作用
2.基本类型对于const是透明的。
3.const限定它的“直接右边”
3.1常量指针
3.2指针常量
4.主要应用场景
5.权限在传递时可以同等传递,也可以缩小传递,但不能扩大
1.作用
定义常量 ( 不能修改 , 不能改写 ),只读。 例如 const int ca = 10; ca=20;//error2.基本类型对于const是透明的。
例如const int ca=10;int const cb=10;等价int main()
{int a = 10; //可读可写a = 20;//写printf("%d\n", a);//读const int ca = 10;//只读,不能写a = ca;//ok,对于ca是读//ca = 20;//error,ca不能写int const cb = 10;//等价ca的定义return 0;
}
3.const限定它的“直接右边”
此条主要用于区别指针常量和常量指针。
3.1常量指针
常量指针:如果在定义指针变量的时候,数据类型前用const修饰,被定义的指针变量就是指向常量的指针变量,指向常量的指针变量称为常量指针,格式如下
const int *p = &a; //常量指针
基本类型对于const是透明的,所以const直接修饰*p,所以p=&a;是可以的的,*p=100;是错误的。
3.2指针常量
指针常量:顾名思义它就是一个常量,但是是指针修饰的。
格式为:
int * const p //指针常量
const直接修饰p,所以p=&a;是错误的,*p=100;是可以的。
具体用法,代码如下:
int main()
{int a = 10;int b = 20;int* p = &a;*p = 100;//a=100; 写p = &b;//写const int* p1 = &a;//*p1 = 100;//错误p1 = &b;//可以int c = *p1;//可以//int* p2 = p1;//不可以,类型不匹配const int* p2 = p1;//可以int const* p3 = &a;//等价p1//*p3=100;//错误p3 = &b;//可以int* const p4 = &a;*p4 = 100;//p4 = &b;//错误return 0;
}
4.主要应用场景
如果函数形参是指针 , 同时不允许修改实参的值 , 那么在指针前面加 const。 例如下面的函数声明 ( 注意加 const 的地方 ):size_t strlen(const char* str);
char* strcpy(char* strDestination, const char* strSource);
char* strcat(char* strDestination, const char* strSource);
int strcmp(const char* string1, const char* string2);
5.权限在传递时可以同等传递,也可以缩小传递,但不能扩大
int main()
{int a = 10;int b = 20;int* p = &a;*p = 100;p = &b;*p = 200;const int ca1 = 100;//int *p1 = &ca1;//error//*p1 = 200;const int* p2 = &ca1;//*p2 = 200;//errorp2 = &a;//ok//int *const p3 = &ca1;//error//p3 = &a;//*p3 = 100;const int* const p4 = &ca1;//p4 = &a;//error//*p4 = 100;//errorreturn 0;
}
更多推荐
const用法,常量指针,指针常量,及const主要应用场景
发布评论