我们先回顾下C语言中的const:
#include <stdio.h>
int main()
{
const int c = 0;
int* p = (int*)&c;
printf("Begin...\n");
*p = 5;
printf("c = %d\n", c);
printf("*p = %d\n", *p);
printf("End...\n");
return 0;
}
gcc编译输出结果,c从0变成了5:
g++编译运行结果,c的值还是为0:
C++在C语言的基础上对const进行了进化处理
C语言中的const变量
C++中的 const 常量
C++ 中的 const 常量与宏定义的不同
#include <stdio.h>
void f()
{
#define a 3 // 整个文件都可以使用a, define没有作用域概念
const int b = 4; // b有作用域概念,只有f函数可以看到
}
void g()
{
printf("a = %d\n", a);
//printf("b = %d\n", b); // 编译报错,看不到变量b
}
int main()
{
const int A = 1;
const int B = 2;
int array[A + B] = {0};
int i = 0;
for(i=0; i<(A + B); i++)
{
printf("array[%d] = %d\n", i, array[i]);
}
f();
g();
return 0;
}
gcc编译会报错:
因为在C语言中,const修饰的变量是只读变量,也就是说A+B的结果要在运行期才能知道,因此编译出错。
g++编译,则能编译通过:
本文链接:http://so.lmcjl.com/news/24099/