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

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

问题描述

是否有可能对某些结构成员设置默认值?
我试过以下,但它会导致语法错误:

  typedef结构
{
  INT标志= 3;
} MYSTRUCT;

错误:

  $ gcc的-o调用testIt test.c的
test.c的:7:错误:预期':',',',',','}'或'__attribute__'之前'='令牌
test.c的:在函数'主':
test.c的:17:错误:'结构<&匿名GT;没有名为'标志'成员


解决方案

结构是一个的数据类型的。你不为数据类型给出的值。你给值的数据类型实例/对象。结果
因此,没有,这是不可能的C.

相反,你可以写一个函数,它执行初始化结构实例。

另外,你可以这样做:

 结构MyStruct_s
{
    INT ID;
} MyStruct_default = {3};typedef结构MyStruct_s MYSTRUCT;

然后总是初始化新的实例为:

  MYSTRUCT mInstance = MyStruct_default;

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’

解决方案

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;

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

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