Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array with constant size (global vs stack)

Tags:

c

gcc

When I tried this code it works:

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

Even though this didn't work:

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

}

I have read all posts here about arrays with constant sizes, but I can't understand why when declaring arry in main it works.

like image 677
A.M.M Avatar asked Dec 28 '22 12:12

A.M.M


1 Answers

The issue here is that const in C doesn’t result in a true constant.

When you write const int i = 5 what you have is a read-only variable and not a constant. In C99 an array dimensioned with i is a variable length array (VLA). VLAs are only available for stack allocated variables, hence the compilation error you see.

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

#define ARRAY_SIZE 5
int arry[ARRAY_SIZE];

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

In fact, even for an array of automatic storage (i.e. stack allocated local variable) you should avoid a VLA since they incur a runtime overhead.

like image 59
David Heffernan Avatar answered Jan 06 '23 07:01

David Heffernan