> On 13 Apr 2021, at 05:21, Barry Smith <[email protected]> wrote:
>
>
> https://stackoverflow.com/questions/201101/how-to-initialize-all-members-of-an-array-to-the-same-value
> seems to indicate one can initialize all entries in C with one {0} but who
> trusts the web or all compilers.
>
> Have you tried the C form?
This is in the C99 standard
(http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf)
Section 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."
So if I write
int foo[4] = {0};
then the first entry is initialised to zero and subsequent entries are
initialised according to the rules for static storage. Those rules are 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"
We're an aggregate, so we recurse and find that each member is an arithmetic
type, so each entry is initialised to zero.
So a conforming C99 compiler _must_ accept {0} as an initializer list and
initialise all entries of the array to zero.
Lawrence