const
const修饰的变量不能再作为左值,初始化后值不能被修改
C和C++const的区别
C语言中const修饰的值是常变量,不是常量,只是不能作为左值被修改
void main ()
{
const int a = 20;
int array[a] = {}; //错误
int * p = (int*)&a;
*p = 30;
//30 30 30,可以通过指针修改值
printf("%d %d %d",a,*p,*(&a) );
}
C++ const用立即数初始化叫常量,必须初始化,所有出现常量名字的地方都在编译阶段被常量的初始化值替换;若用另一个const初始化则叫常变量与C中相同
int main ()
{
const int a = 20;
int * p = (int*)&a;
*p = 30; //把a内存对应的值改为30
//20 30 20
printf("%d %d %d",a,*p,*(&a) ); //-> printf("%d %d %d",20,*p,20);
}
int main ()
{
int b = 20;
const int a = b; //这样就退化成了常变量和C中一样
int array[a] = {}; //错误
int * p = (int*)&a;
*p = 30;
//30 30 30
printf("%d %d %d",a,*p,*(&a) );
}
标签:初始化,20,int,30,C++,理解,printf,const
From: https://www.cnblogs.com/KongJiBlogs/p/17229802.html