C++进阶:新人易入的那些坑 --1.常量、常指针和指针常量

时间:2023-03-09 00:12:37
C++进阶:新人易入的那些坑 --1.常量、常指针和指针常量

声明:以下内容B站/Youtube学习笔记,https://www.youtube.com/user/BoQianTheProgrammer/ Advanced C++.

 /*
why use const
a)Guards against inadvertent write to the variable
b)Self documenting
c)Enables compiler to do more optimization,making code tighter,faster
d)const means the variable can be put in ROM
*/
//const
// A compile time constraint that an object can not be modified int main()
{
const int i = ;
//i = 7; wrong
//如何修改i的值呢?
const_cast<int&>(i) = ; int j;
static_cast<const int&>(j) = ;//wrong,此时j被转成const const int *p1 = &i;//data is const,pointer is not
p1++;
int * const p2;//pointer is const,data is not
const int* const p3;//data and pointer are both const int const *p4 = &i;
const int *p4 = &i;
//If const is on the left of *,data is const
//If const is on the right of *,pointer is const
}