default value for struct member in C

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

    Structure is a data type. You don't give values to a data type. You give values to instances/objects of data types.
    So no this is not possible in C.

    Instead you can write a function which does the initialization for structure instance.

    Alternatively, You could do:

    struct MyStruct_s 
    {
        int id;
    } MyStruct_default = {3};
    
    typedef struct MyStruct_s MyStruct;
    

    And then always initialize your new instances as:

    MyStruct mInstance = MyStruct_default;
    
    0 讨论(0)
  • 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"};

    0 讨论(0)
  • 2020-11-27 11:51

    An initialization function to a struct is a good way to grant it default values:

    Mystruct s;
    Mystruct_init(&s);
    

    Or even shorter:

    Mystruct s = Mystruct_init();  // this time init returns a struct
    
    0 讨论(0)
  • 2020-11-27 11:52

    I think the following way you can do it,

    typedef struct
    {
      int flag : 3;
    } MyStruct;
    
    0 讨论(0)
提交回复
热议问题