const
1、const可以取代宏,const有类型,宏没有类型
2、const修饰的变量称为常变量
3、合理使用const修饰变量,可以增强程序的健壮性。
const的3种修饰
const的位置和int的位置无关
1、修饰普通变量
int main(void){
const int a = 1;
a = 2; //编译不过
printf("%d",a);
return 0;
}
2、修饰指针(*在const之前)
int main(void){
int a = 1;
int b = 2;
int* const p = &a; //除了指向a,p不能再指向其他地址
p = &b;//编译不过
*p = &b;//编译可过
return 0;
}
3、修饰指针指向(*在const之后)
int main(void){
int a = 1;
int b = 2;
int const * p = &a; //除了指向a,p不能再指向其他地址
*p = &b;//编译不过
p = &b;//编译可过
return 0;
}