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

前端 未结 15 2707
予麋鹿
予麋鹿 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:39

    In (ANSI) C99, you can use a designated initializer to initialize a structure:

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

    Edit: Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration." (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)

提交回复
热议问题