Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

gcc - Is an empty initializer list valid C code?

It is common to use {0} to initialize a struct or an array but consider the case when the first field isn't a scalar type. If the first field of struct Person is another struct or array, then this line will result in an error (error: missing braces around initializer).

struct Person person = {0};

At least GCC allows me to use an empty initializer list to accomplish the same thing

struct Person person = {};

But is this valid C code?

Also: Is this line guaranteed to give the same behavior, i.e. a zero-initialized struct?

struct Person person;
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, an empty initializer list is not allowed. This can also be shown by GCC when compiling with -std=c99 -pedantic:

a.c:4: warning: ISO C forbids empty initializer braces

The reason is the way the grammar is defined in §6.7.9 of the 2011 ISO C Standard:

initializer:
         assignment-expression
         { initializer-list }
         { initializer-list , }
initializer-list:
         designation(opt) initializer
         initializer-list , designation(opt) initializer

According to that definition, an initializer-list must contain at least one initializer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...