-1

I have a struct array. Only a few index locations need to be initialized. Is there a compiler attribute that ensures that the uninitialized combinations are init'd to 0 ?

For example:

If I have a statically init'd struct array as below, how can I ensure that the remaining 3 elements in that array (which are not explicitly pre-init'd) are zero'd out ?

typedef struct foo_s {
    int a;
    int b;
} foo_t;

foo_t foo_array[4] = {
    { .a = 1, .b = 2 },
};

Thanks,

TheLoneJoker
  • 1,589
  • 1
  • 23
  • 36

1 Answers1

1

The behavior you want is already part of standard C. There are no "half-initialized" variables; if you only initialize part of something, then all remaining elements will be zero-initialized.

Besides, you say (in your title) that this array is global. That means it has static storage duration, so it will be zero-initialized even if you don't provide any initializer at all.

Quoting C99 on aggregate initializers:

6.7.8/19:

[...] all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

6.7.8/21:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

6.7.8/10:

If an object that has static 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;
  • if it is a union, the first named member is initialized (recursively) according to these rules.
melpomene
  • 84,125
  • 8
  • 85
  • 148