Array with constant size (global stack vs)

When I tried this code, it works:

const int i = 5; int main() { int arry[i]; } 

Even if this did not work:

 const int i = 5; int arry[i]; int main() { } 

I read all the posts here about constant-sized arrays, but I can't figure out why it works when declaring arry in main.

+4
source share
2 answers

The problem is that const in C does not lead to a true constant.

When you write const int i = 5 what you have is a read-only variable, not a constant. In C99, an array whose size is i is a variable length array (VLA). VLAs are only available for stacked variables, therefore you see a compilation error.

If you need an array with a global scope, you must switch to a macro.

 #define ARRAY_SIZE 5 int arry[ARRAY_SIZE]; 

This is true because 5 is a literal, which is a true constant.

In fact, even for an automatic storage array (i.e. a distributed local table), you should avoid VLAs, as they incur overhead at runtime.

+9
source

Version 2 is simply not valid C because i is a read-only variable and not a constant constant compilation. If you want it to work, you can use malloc and free (or a #define for size).

Version 1 uses a variable length array, which is a standard feature of C99. gcc supports this syntax in pre-C99 code as an extension. If you compiled your code as C90 and included -pedantic , you will get a warning that the ISO C90 forbids variable length array 'arry' .

+1
source

All Articles