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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With