If all you want to do is to initialize everything to zeroes, you can initialize your struct
with {0}
, which is always going to initialize everything to 0
.
From the C standard, 6.7.8 (emphasis mine):
20. If the aggregate or union contains elements or members that are aggregates or unions, these rules apply recursively to the subaggregates or contained unions. If the initializer of a subaggregate or contained union begins with a left brace, the initializers enclosed by that brace and its matching right brace initialize the elements or members of the subaggregate or the contained union. Otherwise, only enough initializers from the list are taken to account for the elements or members of the subaggregate or the first member of the contained union; any remaining initializers are left to initialize the next element or member of the aggregate of which the current subaggregate or contained union is a part.
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.
In plain terms, {0}
is the correct initializer for any aggregate type. So, struct foo bar = { 0 };
initializes the first element of bar
to 0
, and the rest are initialized recursively to their respective zero values.
If you want to initialize the members to non-zero values, you may want to write a function. Note that the "zero" value is correct for each data type. This may not be all-bits-zero for pointers and/or floating-point values.
gcc
with -Wall
option by default warns if you don't have "enough" braces, but the warning is harmless if you know what you're doing. You can disable the with -Wno-missing-braces