default value for struct member in C

后端 未结 16 2258
-上瘾入骨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:31

    you can not do it in this way

    Use the following instead

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

    You can use macro to define and initialize your instances. this will make easiier to you each time you want to define new instance and initialize it.

    typedef struct
    {
       int id;
       char* name;
    }employee;
    
    #define INIT_EMPLOYEE(X) employee X = {.id = 0, .name ="none"}
    

    and in your code when you need to define new instance with employee type, you just call this macro like:

    INIT_EMPLOYEE(emp);
    

提交回复
热议问题