default value for struct member in C

后端 未结 16 2254
-上瘾入骨i
-上瘾入骨i 2020-11-27 10:53

Is it possible to set default values for some struct member? I tried the following but, it\'d cause syntax error:

typedef struct
{
  int flag = 3;
} MyStruct         


        
16条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 11:26

    If you only use this structure for once, i.e. create a global/static variable, you can remove typedef, and initialized this variable instantly:

    struct {
        int id;
        char *name;
    } employee = {
        .id = 0,
        .name = "none"
    };
    

    Then, you can use employee in your code after that.

提交回复
热议问题