C中结构成员的默认值 [英] default value for struct member in C

查看:27
本文介绍了C中结构成员的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

错误:

$ 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 中是不可能的.

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.

或者,您可以这样做:

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;

这篇关于C中结构成员的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆