简体   繁体   中英

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.

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.

The size of an array must be a constant. You can fix this by declaring y as const .

const int y=5;
int arr[y]; 

As for why this worked in main , g++ does allow a variable length array in block scope as an extension. It is not standard C++ however.

Both shouldn't be used, one works because (as @eerorika said) automatic length arrays are allowed on runtime, but global arrays need to have static storage.

If you want to declare an array with a variable size (eg given by std::cin) you would do something along the lines of:

int x;
std::cin >> x;
const int n = x;
float arr[n];

But you wouldn't be able to set it to contain just zeros with float arr[n] = {0} (if you need to add to a value in the array, not being sure you set it), you would need to use a loop like that

for(int i = 0; i < n; i++)
{
    arr[i] = 0;
}

The type-system of C++ handles these C-like arrays in a way that it defines arr2 from your example of type int[5] . So, yes the number of elements of the array is part of the type!

This puts some constraints on what you are allowed to use in the definition of C-like arrays. Ie this number needs to have static storage , needs to be immutable and needs to be available at compile time .

So, you might want to change your code to something like the following, which will have another goodie. It initializes the array in a proper way:

int arr2[] = {0, 0, 0, 0, 0};   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM