(一)const与基本数据类型
int x=3; //x是变量,值可以更改
const int x=20; //x是常量,值不可以更改
(二)const与指针类型
const int *p=NULL;等价于int const *p=NULL;
举例说明:
(1)
int x=3;
const int *p=&x;
p=&y; //正确
*p=4; //错误
由于const修饰*p,因此可以将p的内容改变但是*p不可以改变
(2)
int x=3;
int * const p=&x;
p=&y; //错误的
由于const修饰的是p而不是*p,因此P的内容不可以被随意更改
(3)
const int x= 3;
const int * const p =&x;
p=&y; //错误
*p=4; //错误
(三)const与引用
int x=3;
const int &y=x;
x=10; //正确
y=20; //错误