1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Harry
  • 4,524
  • 4
  • 42
  • 81
  • 1
    No, everything will (should AFAIK) be initialized to zeros. –  Oct 23 '22 at 10:39
  • I guess you'd prefer explicit initialization in case if different compilers behave differently. Use a function to create a new struct and make sure that every struct initialized properly inside that function. – Ivan Silkin Oct 23 '22 at 10:39
  • In C youd normally work with allocated pointers to these structs, so some T_create function would have to be implemented so all initialization details are covered there explicitly. If its all zero then its just a calloc wrapper. – carce-bo Oct 23 '22 at 10:42
  • 1
    Note that using `{}` as initializer is invalid in C before the upcoming C23 standard. – Some programmer dude Oct 23 '22 at 10:43

1 Answers1

2

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 };
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335