Search code examples
cstructinitializationdeclarationzero-initialization

C nested struct initialization - what is initialized?


Let's say I have struct S:

typedef struct
{
  int x;
  int y;
} S;

Then:

S s; // s is uninitialized here.

And:

S s = {}; // s is initialized (zeroed) here.

Now let's say I have struct T:

typedef struct
{
  S s1;
  S s2;
} T;

And I initialize it like this:

  T t = {}; // is t completely initialized?

I'm just guessing that t.s1.x can contain a random value, right?

Do I have to write:

T t = {{}, {}};

Is it necessary to have t.s1 and t.s2 initialized / zeroed?

Then, if I write:

int a[8];

Is it 8 zeroes, or 8 random values, that most likely are zeroes?

Again, I'm guessing I should write

int a[8] = {};

... to have 8 certain zeroes, but I'm not sure.

What about:

T[8] = {};

Is it 8 initialized Ts, or 8 uninitialized / random Ts?

How do you properly initialize / zero such nested structs and arrays?

By initialization I mean just having zeroes everywhere.


Solution

  • Whether the object s is initialized in this declaration

    S s; // s is uninitialized here.
    

    depends on where the declaration is placed. If the declaration is placed in a file scope then the object is zero-initialized as an object with static storage duration. If the declaration is placed in a block scope then the object is uninitialized as an object with automatic storage duration and has indeterminate values.

    These all declarations

    S s = {}; // s is initialized (zeroed) here
    T t = {}; // is t completely initialized?
    T t = {{}, {}};
    int a[8] = {};
    

    are invalid in C because you may not use empty braces to initialize objects.

    To zero initialize for example the object t in a block scope you should write for example

    T t = { 0 };
    

    or

    T t = { { 0 } };
    

    To zero-initialize the array a (all its elements) in a block scope you should write for example

    int a[9] = { 0 };