Why initialization of a variable-sized object is not allowed using const

This is not true because a variable-sized object cannot be initialized.

int size = 4;
int array[size] = {1};

size- this is a variable, but does the compiler know when it creates array(Not sizeassigned an initial value of 4 at compile time?)? Let it sizechange after that , why will this be a problem? I mean, these are sequential instructions, what can change the value sizebefore declaring the array?

Second question: Why is this not allowed:

const int size = 4;
int array[size] = {1};

I declare sizeas const. I know that const! = Read-only, and that declaring sizeas a macro is the right way to get around this. But if I promise the compiler to use const, that I will not change the value size, why is this not allowed?

+4
source share
1 answer

The answer to the first question is "because the language specification says so." Although the compiler can infer the size of the array, this requires some static analysis, which is not trivial if the size of the array is not a constant expression of compilation time.

, VLA : , I, , , , VLA , undefined. , ( ) ().

: :

, you (, Microsoft - C - , C99, 15 .). , C , C99. , C11, VLA ( ).

+6

All Articles