default value for struct member in C

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

    Create a default struct as the other answers have mentioned:

    struct MyStruct
    {
        int flag;
    }
    
    MyStruct_default = {3};
    

    However, the above code will not work in a header file - you will get error: multiple definition of 'MyStruct_default'. To solve this problem, use extern instead in the header file:

    struct MyStruct
    {
        int flag;
    };
    
    extern const struct MyStruct MyStruct_default;
    

    And in the c file:

    const struct MyStruct MyStruct_default = {3};
    

    Hope this helps anyone having trouble with the header file.

提交回复
热议问题