开发者

Global - Local difference in the init of an array in c

开发者 https://www.devze.com 2023-01-02 10:29 出处:网络
W开发者_JS百科hy this dont work: int size = 2; int array[size]; int main() { return 0; } It says the error: array bound is not an integer constant

W开发者_JS百科hy this dont work:

int size = 2;
int array[size];

int main() {
  return 0;
}

It says the error: array bound is not an integer constant

And this work:

int size = 2;

int main() {
  int array[size];
  return 0;
}

Anyone knows the reason? thanks


In C++ or C89/90 neither works. These languages require that array size is an Integral Constant Expression (ICE). In your examples size is not an ICE. If your C++ or C89/90 compiler allows it, it is nothing else than a non-standard compiler extension.

In C99 the second works because this is how Variable Array Length (VLA) specification is defined. VLA can only be defined in local scope.


Dynamic sized arrays is a feature of C99 and is not included in the current C++ standard at all.

If you are compiling as C++ neither should work. If you change to a const variable then both methods will be allowed by the C++ standard.

0

精彩评论

暂无评论...
验证码 换一张
取 消