const与基本数据类型
int x=3 //变量
const int x=3 //常量
x=4; //编译器会报错,常量不可改变
const 与指针类型
const int *p=NULL;等价于int const *p=NULL;
int* const p=NULL;
const int*const p=NULL; 等价于 int const * const p=NULL;
ex:
int x=3;
const int *p=&x; //const写在*的前面,修饰的是*p,所以*p不能变
p=&y;//正确
*p=4;//错误
int *const p1=&x;//const写在*的后面,修饰的是p,所有p不能变只能指向一个地址
p=&y;//错误
const与引用
int x=3;
const int &y=x;//y是x的别名,但是被const修饰了
x=10;//正确
y=20;//错误
ex:
const int x=3; x=5;//错误
int x=3; const int y=x; y=5;//错误
int x=3; const int *y=&x; *y=5;//错误,const在*之前,修饰的是*y
int x=3; z=4; int * const y=&x; y=&z;//错误,const在*之后,修饰的是y,y的指向不能变
const int x=3; const int &y=x; y=5;//错误
const int x=3; int *y=&x;//错误,定义了一个可变的指针去指向一个不可变的常量
int x=3; const int *y=&x; //可以
#define X 3 //是宏定义,编译的时候计算机不检查语法错误
const int x=3;//都是定义常量,const定义的是有类型的,编译的时候是要检查语法错误的