default value for struct member in C

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

    I agree with Als that you can not initialize at time of defining the structure in C. But you can initialize the structure at time of creating instance shown as below.

    In C,

     struct s {
            int i;
            int j;
        };
    
        struct s s_instance = { 10 ,20 };
    

    in C++ its possible to give direct value in definition of structure shown as below

    struct s {
        int i;
    
        s(): i(10)
        {
        }
    };
    

提交回复
热议问题