const的作用:定义常变量,不允许修改其值。
例如:int const p = 10;如果再给p赋值,p = 20,它是error ; int const p1;也是error ;因为它没有初始化。
const的使用如下:
1、基本的数据类型对于const是透明的。
int const ca = 0; const int cb = 0;ca和cb是等价的。
const放在int的左边和右边都可以,修饰的是ca和cb;
2、const限定它的直接右边。
const放在数据类型之前:const int *cp = &a;int是透明的,看它的时候可以当它不存在,const修饰*cp, 因为它不能再赋值,所以*cp不能做左值;*cp = 100是error;但p = &b是OK。
const放在*之后:int *const cp2 =&a;const修饰cp2,cp2 = &b是error;所以cp2作为直接右边不能做左值,*cp2 = 100是OK。
const放在*之前:int const *cp3 = &a; const修饰*cp3;//cp3等价cp.
3、权限可以缩小或者同等传递,但不能放大。
#include<stdio.h>
int main()
{
int a = 10;
int b = 20;
const int ca = 10;
const int cb = 10;
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;
}