1、C中const的特性
点击(此处)折叠或打开
-
const int x = 5;
- int array[x] = {0}; //错误(在c中常变量不能用做数组下标)
如下所示:
点击(此处)折叠或打开
-
int mian()
-
{
-
const int a = 10;
-
int *p = &a;
-
*p = 20;
-
printf("%d,%d\n", a, *p);
-
return 0;
- }
2、C++中的const
点击(此处)折叠或打开
-
int main()
-
{
-
const int a = 10;
-
int array[a] = {0};
-
-
int *p = (int *)&a;
-
*p = 20;
-
cout<<a<<" "<<*p<<endl;
-
return 0;
- }
与C中的const对比发现,C++中的const是常量,其必须被初始化,且const 对象一旦创建后其值就不能再改变。在编译时,所有的常量a都将被替换为其初始值10。
注意:
当常量的初始值为变量时,其会退化为常变量。
点击(此处)折叠或打开
-
int a = 10;
- const int b = a;
-
int arr[b] = {1}; //错误,常变量不能作数组下标
总结:
(1)C中的const是常变量,本质还是变量;C++中的const是常量。
(2)在编译时,C中的const以变量的方式编译;C++中的const以常量的方式编译,凡是出现常量的地方(编译时初始化)均用常量的值来替换。
(3)在C++中,当常量的初始值为变量时,其会退化为常变量。