【发布时间】:2018-02-07 09:10:08
【问题描述】:
考虑以下代码:
#include <iostream>
using namespace std;
int main()
{
int x = 3;
const int i[] = { 1, 2, 3, 4 };
float f[i[3]];
struct S { int i, j; };
const S s[] = { { 1, 2 }, { 3, 4 } };
double d[s[1].j];
}
它运行没有错误。但是,以下内容:
#include <iostream>
using namespace std;
int x = 3;
const int i[] = { 1, 2, 3, 4 };
float f[i[3]]; // error: array bound is not an integer constant before ']' token|
struct S { int i, j; };
const S s[] = { { 1, 2 }, { 3, 4 } };
double d[s[1].j]; // error: array bound is not an integer constant before ']' token|
int main()
{
return 0;
}
没有,因为它会获取以 cmets 突出显示的错误。谁能给我解释一下这是为什么?
【问题讨论】:
-
我认为是因为 i[3] 不是常数,常数是 i[] 这意味着 i[] 不能指向任何其他内存块,但您仍然可以更改每个i 中的元素。
-
一种猜测是您使用 g++ which has an extension for VLAs 并且不需要本地数组边界是恒定的。
-
请注意,第一个在标准 C++ 中也是无效的,但您的编译器允许它作为扩展。
-
第一个例子我收到很多警告。
-
使用正确的编译器设置,第一个代码示例也将无法编译 src/test.cpp:在函数“int main()”中:src/test.cpp:8:17:错误:ISO C++ 禁止变长数组'f' [-Werror=vla] float f[i[3]];
标签: c++ compiler-errors compilation constants