0

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]);
    }
3
  • If you declare simply int a[5] its contents are not initialized. That's all. Commented Nov 15, 2022 at 11:17
  • Well, int a[5]={}; is UB since it's a syntax error... Commented Nov 15, 2022 at 12:20
  • And also another example of gcc being wildly non-conforming when the crappy default settings are active... No diagnostic even with -Wall -Wextra. Commented Nov 15, 2022 at 12:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.