default value for struct member in C

2020-01-25 05:00发布

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;

Errors:

$ gcc -o testIt test.c 
test.c:7: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
test.c: In function ‘main’:
test.c:17: error: ‘struct <anonymous>’ has no member named ‘flag’

标签: c struct
7条回答
再贱就再见
2楼-- · 2020-01-25 05:25

Another approach to default values. Make an initialization function with the same type as the struct. This approach is very useful when splitting large code into separate files.

struct structType{
  int flag;
};

struct structType InitializeMyStruct(){
    struct structType structInitialized;
    structInitialized.flag = 3;
    return(structInitialized); 
};


int main(){
    struct structType MyStruct = InitializeMyStruct();
};
查看更多
Rolldiameter
3楼-- · 2020-01-25 05:33

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
查看更多
Emotional °昔
4楼-- · 2020-01-25 05:44

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.

查看更多
迷人小祖宗
5楼-- · 2020-01-25 05: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;
查看更多
Deceive 欺骗
6楼-- · 2020-01-25 05:46

Another approach, if the struct allows it, is to use a #define with the default values inside:

#define MYSTRUCT_INIT { 0, 0, true }

typedef struct
{
    int id;
    int flag;
    bool foo;
} MyStruct;

Use:

MyStruct val = MYSTRUCT_INIT;
查看更多
女痞
7楼-- · 2020-01-25 05:48

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)
    {
    }
};
查看更多
登录 后发表回答