/*
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 = 9;
//i = 7; wrong
//如何修改i的值呢?
const_cast<int&>(i) = 7;
int j;
static_cast<const int&>(j) = 7;//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
}
声明:以上内容B站/Youtube学习笔记,https://www.youtube.com/user/BoQianTheProgrammer/ Advanced C++.