How to initialize a struct in accordance with C programming language standards

前端 未结 15 2891
予麋鹿
予麋鹿 2020-11-21 22:59

I want to initialize a struct element, split in declaration and initialization. This is what I have:

typedef struct MY_TYPE {
  bool flag;
  short int value;         


        
15条回答
  •  野的像风
    2020-11-21 23:43

    C programming language standard ISO/IEC 9899:1999 (commonly known as C99) allows one to use a designated initializer to initialize members of a structure or union as follows:

    MY_TYPE a = { .stuff = 0.456, .flag = true, .value = 123 };
    

    It is defined in paragraph 7, section 6.7.8 Initialization of ISO/IEC 9899:1999 standard as:

    If a designator has the form
    . identifier
    then the current object (defined below) shall have structure or union type and the identifier shall be the name of a member of that type.

    Note that paragraph 9 of the same section states that:

    Except where explicitly stated otherwise, for the purposes of this subclause unnamed members of objects of structure and union type do not participate in initialization. Unnamed members of structure objects have indeterminate value even after initialization.

    In GNU GCC implementation however omitted members are initialized as zero or zero-like type-appropriate value. As stated in section 6.27 Designated Initializers of GNU GCC documentation:

    Omitted field members are implicitly initialized the same as objects that have static storage duration.

    Microsoft Visual C++ compiler should support designated initializers since version 2013 according to official blog post C++ Conformance Roadmap. Paragraph Initializing unions and structs of Initializers article at MSDN Visual Studio documentation suggests that unnamed members initialized to zero-like appropriate values similarly to GNU GCC.

    ISO/IEC 9899:2011 standard (commonly known as C11) which had superseded ISO/IEC 9899:1999 retains designated initializers under section 6.7.9 Initialization. It also retains paragraph 9 unchanged.

    New ISO/IEC 9899:2018 standard (commonly known as C18) which had superseded ISO/IEC 9899:2011 retains designated initializers under section 6.7.9 Initialization. It also retains paragraph 9 unchanged.

提交回复
热议问题