“直男”与“暖男”的区别——const
程序员文章站
2023-12-26 16:49:27
1 int wife = 24; 2 int girlfriend = 18; 3 4 //直男型 5 int const * zhi_nan; 6 zhi_nan = &wife;//正确 7 zhi_nan = &girlfriend;//正确 8 *zhi_nan = 20;//错误 9 10... ......
1 int wife = 24; 2 int girlfriend = 18; 3 4 //直男型 5 int const * zhi_nan; 6 zhi_nan = &wife;//正确 7 zhi_nan = &girlfriend;//正确 8 *zhi_nan = 20;//错误 9 10 //暖男型 11 int * const nuan_nan; 12 nuan_nan = &wife; 13 *nuan_nan = 26;//可修改wife值 14 nuan_nan = &girlfriend;//错误,不允许指向其他地址 15 16 //超级暖男型 17 const int * const superman;//不允许指向其他地址,也不能修改变量的值 18 superman = &wife; 19 *superman = 28;//错误,无法修改wife值 20 superman = &girlfriend;//错误,不允许访问其他地址 21 22 //总结:看const离int近还是离指针变量名近,离谁近就修饰谁,谁就不能变!