arrayscinitializationstorage-duration

When do the elements of array store garbage value in C programming?


I was writing a code to learn about arrays and I noticed that if an array is declared as

a[5];

It's storing garbage values as its' elements While

a[5] = {};

Is storing 0 as all the elements.

Can someone explain what is happening and how these values are being stored ?

I wondered if this was a static data type but it doesn't seem to be that


    #include<stdio.h>
   
    void increment();
    
    int main()
    {
        increment();
        increment();
        increment();
    }
    
    void increment()
    {
        int a[5]={};
        static int b[5]={1,2,3,4,5};
        int i;
        for(i=0;i<=4;i++)
        {
            a[i]++;
            b[i]++;
        }
        printf("%d %d\n",a[1],b[1]);
    }

Solution

  • Variables with automatic storage duration (declared in a block scope without the storage class specifier static) stay uninitialized if they are not initialized explicitly.

    This declaration

    int a[5] = {};
    

    is invalid in C. You may not specify an empty braced list. You have to write for example

    int a[5] = { 0 };
    

    or

    int a[5] = { [0] = 0 };
    

    In this case the first element is initialized by zero explicitly and all other elements are zero-initialized implicitly.

    Compilers can have their own language extensions that allow to use some constructions that are not valid in the C Standard.

    If an array has static storage duration (either declared in file scope or has the storage class specifier static) it is initialized implicitly (for arithmetic types it is zero-initalzed) if it was not initialized explicitly.

    Arrays with static storage duration preserve their values between function calls.

    Within the function increment

    void increment()
    {
        int a[5]={ 0 };
        static int b[5]={1,2,3,4,5};
        /... 
    

    the array a with automatic storage duration is initialized each time when the function gets the control.

    The array b with static storage duration is initialized only once before the program startup.