Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't we initialize automatic array variables?

Tags:

c

I was referring to the book "Theory and Problems of Programming with C" by Gottfried (Schaum's Outline series, 2nd Edition, 1996). On page number 243 section 9.1 in chapter 9 on Arrays, it says:

Automatic arrays, unlike automatic variables, cannot be initialized. However, external and static array definitions can include the assignment of initial values if desired.

I did not understand the meaning of this highlighted statement. I tried to initialize array (with and without auto keyword) inside the function and do not see any issue with it.

void func1 (void)
{
    auto int array1[5] ={1,0,4,1,5};
    charVar1='M';
    printf("%d", *(array1+4));
}

Added the image of the pageenter image description here

like image 229
Jon Wheelock Avatar asked Jan 23 '26 12:01

Jon Wheelock


1 Answers

To answer the first part

Automatic arrays, unlike automatic variables, cannot be initialized

assuming the "Automatic arrays" are actually "array data structure of automatic storage duration whose length is determined at run time"

Yes, here what is referred to is called a variable length array. It cannot be initialized as for the simple logic, the size is determined at runtime.

To quote the C11 standard, chapter §6.7.9, Initialization (emphasis mine)

The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

Otherwise, for a local variable without any storage class specifier, defaults to auto and an automatic array of non-VLA type, can be initialized, for sure.

like image 54
Sourav Ghosh Avatar answered Jan 25 '26 03:01

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!