声明为const的变量,可确保变量的取值在整个生命周期内都固定为初始化值!
const指针有三种:
First:指针指向的数据为常量,不能修改,但可以修改指针包含的地址,既指针可以指向其他地方。
1 int HoursInDay = 24; 2 const int* pInteger = &HoursInDay;//cannot use pInteger to change HoursInday 3 int MothsInYear = 12; 4 pInteger = &MonthsInYear;//OK 5 *pInteger = 13;//fail:cannot change data 6 int* pAnotherPointerToInt = pInteger; //fails:cannot assign const to non-const
Second:指针包含的地址是常量,不能修改,但可以修改指针指向的数据。
1 int DaysInMoth = 30;2 int* const pDaysInMoth = &DayInMoth; 3 *pDaysInMoth = 31;//OK 4 int DaysInLunarMonth = 28; 5 pDayInMoth = &DaysInLunarMonth;//fails:Cannot change address!
Third:指针包含的地址以及它指向的值都是常量,不能修改。
1 int HoursInDay = 24; 2 const int* const pHoursInDay = &HoursInDay; 3 *pHoursInDay = 25;//fails:cannot change pointed value 4 int DaysInMonth = 30; 5 pHoursInDay = &DaysInMonth;//fails: cannot change pointer value
讲指针传递给函数时,这些形式的const很有用。函数参数应声明为最严格的const指针,以确保函数不会修改该指针指向的值,让函数更容易维护。