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

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

    I see you've already received an answer about ANSI C 99, so I'll throw a bone about ANSI C 89. ANSI C 89 allows you to initialize a struct this way:

    typedef struct Item {
        int a;
        float b;
        char* name;
    } Item;
    
    int main(void) {
        Item item = { 5, 2.2, "George" };
        return 0;
    }
    

    An important thing to remember, at the moment you initialize even one object/ variable in the struct, all of its other variables will be initialized to default value.

    If you don't initialize the values in your struct, all variables will contain "garbage values".

    Good luck!

提交回复
热议问题