在C语言中const是运行时才会对变量进行初始化,编译时只是定义。所以C语言中const变量不能用于成为数组长度等作为编译时的常量。C语言const变量在运行时改变了是可以再次读出改变后的值的。
而在C++中const变量的值在编译时就已经确定了,当const变量的值改变时,const的变量值是不会得到更新的。
以下的这几行代码在C和C++中都会改变const变量的值,只不过C++中const变量在编译的时候已经确定了,而C中的const变量可以在运行时改变后再次读取。以下代码详述了C++中的const变量确实被改变了。
int main(){
constinti = 0;
int*j = (int*)&i;
*j = 1;
printf("%d,%d", i, *j);
system("pause");
return 0;
}
在C中,运行以上代码输出1,1
#include<iostream>
usingnamespacestd;
intmain(void){
constinti=0;
int*j = (int*)&i;
*j = 1;
printf("%d,%d", i, *j);
system("pause");
return0;
}
在C++中,运行以上代码输出为0,1