default value for struct member in C

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

    If you are using gcc you can give designated initializers in object creation.

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

    Or , simply use like array initialization.

    employee e = {0 , "none"};

提交回复
热议问题