开发者

Initializing nested structures without defining all fields

开发者 https://www.devze.com 2022-12-18 07:33 出处:网络
I have a set of structs, defined as follows: typedef struct { int index; int array[10]; } Item; typedef struct

I have a set of structs, defined as follows:

typedef struct
{
    int index;
    int array[10];
}
Item;

typedef struct
{
    Item A;
    Item B;
    Item C;
}
Collection;

And I want to declare a variable of type Collection as follows:

Collection collection =
{
    { 1, 0 },  /* item A */
    { 2, 0 },  /* item B */
    { 3, 0 }   /* item C */
};

Will this set the three index variables to 1, 2, and 3, while at the same time initializing all three array[] variables with zero?

开发者_如何学C

It appears to be working on my compiler, but I would like to know if this is the standard behaviour.


There should be additional braces around the zeros to make them valid array initializers:

Collection collection =
{
    { 1, {0} },  /* item A */
    { 2, {0} },  /* item B */
    { 3, {0} }   /* item C */
};

Apart from that it will correctly initialize the structure.

The inizializer is also valid without the additional braces, but you will get compiler warnings and it's much less confusing if initializers for subaggregates are made explicit. For the details see section 6.7.8 in the C99 standard that dirkgently refers to in his answer, especially 6.7.8 (20) and the examples in 6.7.8 (29).


This is standards compliant. See the section -- 6.7.8 Initialization. Further, you can use designated initializers in C99 conforming compilers.

0

精彩评论

暂无评论...
验证码 换一张
取 消