Search code examples
c++variable-length-array

Why should global array size be an integer constant?


In C++ I tried declaring a global array of some size. I got the error:

array bound is not an integer constant before ‘]’ token

But when I declared an array of the same type in the main() function it is working fine.

Why is there different behaviour here?

int y=5;
int arr[y];         //When I comment this line it works fine

int main()
{
    int x=5;
    int arr2[x];        // This line doesn't show any error.
}

Edit: Many are suggesting this question is a duplicate of Getting error "array bound is not an integer constant before ']' token". But that question doesn't answer why there is different behaviour.


Solution

  • Both examples are ill-formed in C++. If a compiler does not diagnose the latter, then it does not conform to the standard.

    Why there is a different behaviour here?

    You use a language extension that allows runtime length automatic arrays. But does not allow runtime length static arrays. Global arrays have static storage.

    In case you are using GCC, you can ask it to conform to the standard by using the -pedantic command line option. It is a good idea to do so in order to be informed about portability problems.