Search code examples
arrayscinitializationstorage-duration

Initializing local array variable in C


Is it guaranteed that first element in the below array will be set to 1 and all others to 0, or is it compiler defined behavior?

#include <stdint.h>

int main () {
    uint16_t arr[10] = {1};
}

Solution

  • From the C Standard (6.7.9 Initialization)

    19 The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject;154) all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

    and

    10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

    — if it has pointer type, it is initialized to a null pointer;

    — if it has arithmetic type, it is initialized to (positive or unsigned) zero;

    — if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

    — if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

    So as the element type of your array is an arithmetic type then all elements of the array except the first element that has an explicit initializer will be zero-initialized.

    Pay attention to that according to the C standard the function main without parameters shall be declared like

    int main( void )