leg*_*s2k 1 c++ scope const definition
我试过了
const int i[] = { 1, 2, 3, 4 };
float f[i[3]]; // g++ cries "error: array bound is not an integer constant"
int main()
{
const int j[] = { 0, 1, 2, 3 };
float g[j[3]]; // compiler is happy :)
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这两个聚合有什么区别?为什么在main()中引用const聚合的元素在全局范围内无效时是有效的?
AnT*_*AnT 10
在C++中,数组声明中的大小必须是积分常量表达式(ICE).根据定义,C++中的ICE不能包含从数组中获取的值,无论它是否是const数组.因此,在这两种情况下i[3]和j[3]不ICE中,不能用作数组声明尺寸.因此,两个声明 - f和g- 在C++中都是非法的.
但是,由于您使用的是GCC,因此在第二种情况下会使用非标准编译器扩展.当您声明一个自动数组时,GCC允许您为数组指定一个非常量大小(即运行时大小)(这基本上是C99的VGA转移到C++).这就是它"快乐"的原因,即使代码在C++中不合法.在-ansi -pedantic-error模式下编译,您应该获得每个声明的诊断消息(错误).