考虑下面的代码段:C++常量和聚集体内部功能体与外
#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;
}
不会,因为它会获取突出显示为注释的错误。任何人都可以向我解释为什么这是?
我认为这是因为我[3]不是常量,常量是我[]它意味着我[]不能指向任何其他块的内存,但你仍然可以改变我内的每个元素。 – apalomer
一个猜测是你使用g ++ [它有一个扩展的VLA](https://stackoverflow.com/questions/5947661/in-c-books-array-bound-must-be-constant-expression-but-why -the-following-cod)并且不需要局部数组边界是恒定的。 –
请注意,第一个在标准C++中也是无效的,但是您的编译器允许它作为扩展。 –