C中struct成员的默认值

default value for struct member in C

是否可以为某些结构成员设置默认值?
我尝试了以下操作,但会导致语法错误:

1
2
3
4
typedef struct
{
  int flag = 3;
} MyStruct;

错误:

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


结构是一种数据类型。您不给数据类型赋值。您为数据类型的实例/对象提供值。
因此,这在C语言中是不可能的。

相反,您可以编写一个对结构实例进行初始化的函数。

或者,您可以执行以下操作:

1
2
3
4
5
6
struct MyStruct_s
{
    int id;
} MyStruct_default = {3};

typedef struct MyStruct_s MyStruct;

然后始终将新实例初始化为:

1
MyStruct mInstance = MyStruct_default;


我同意Als的观点,即您无法在C语言中定义结构时进行初始化。
但是您可以在创建实例时初始化结构,如下所示。

在C中

1
2
3
4
5
6
 struct s {
        int i;
        int j;
    };

    struct s s_instance = { 10 ,20 };

在C ++中,可以在如下所示的结构定义中直接给出值

1
2
3
4
5
6
7
struct s {
    int i;

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


创建一个默认结构,如其他答案所述:

1
2
3
4
5
6
struct MyStruct
{
    int flag;
}

MyStruct_default = {3};

但是,以上代码在头文件中将不起作用-您将收到错误:multiple definition of 'MyStruct_default'。要解决此问题,请在头文件中使用extern代替:

1
2
3
4
5
6
struct MyStruct
{
    int flag;
};

extern const struct MyStruct MyStruct_default;

并在c文件中:

1
const struct MyStruct MyStruct_default = {3};

希望这可以帮助遇到头文件问题的任何人。


您可以使用一些函数来初始化struct,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
typedef struct
{
    int flag;
} MyStruct;

MyStruct GetMyStruct(int value)
{
    MyStruct My = {0};
    My.flag = value;
    return My;
}

void main (void)
{
    MyStruct temp;
    temp = GetMyStruct(3);
    printf("%d
"
, temp.flag);
}

编辑:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
typedef struct
{
    int flag;
} MyStruct;

MyStruct MyData[20];

MyStruct GetMyStruct(int value)
{
    MyStruct My = {0};
    My.flag = value;
    return My;
}

void main (void)
{
    int i;
    for (i = 0; i < 20; i ++)
        MyData[i] = GetMyStruct(3);

    for (i = 0; i < 20; i ++)
        printf("%d
"
, MyData[i].flag);
}


默认值的另一种方法。使用与struct相同的类型创建一个初始化函数。将大代码拆分为单独的文件时,此方法非常有用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct structType{
  int flag;
};

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


int main(){
    struct structType MyStruct = InitializeMyStruct();
};

初始化结构的函数是授予其默认值的好方法:

1
2
Mystruct s;
Mystruct_init(&s);

甚至更短:

1
Mystruct s = Mystruct_init();  // this time init returns a struct