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

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

    You can do it with a compound literal. According to that page, it works in C99 (which also counts as ANSI C).

    MY_TYPE a;
    
    a = (MY_TYPE) { .flag = true, .value = 123, .stuff = 0.456 };
    ...
    a = (MY_TYPE) { .value = 234, .stuff = 1.234, .flag = false };
    

    The designations in the initializers are optional; you could also write:

    a = (MY_TYPE) { true,  123, 0.456 };
    ...
    a = (MY_TYPE) { false, 234, 1.234 };
    

提交回复
热议问题