初始化一个结构为0 [英] Initializing a struct to 0

查看:107
本文介绍了初始化一个结构为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的结构:

  typedef结构
{
    unsigned char型C1;
    unsigned char型C2;
} MYSTRUCT;

什么是初始化这个结构为0,最简单的方法?
将以下就足够了?

  MYSTRUCT _M1 = {0};

或将我需要每个成员明确初始化为0?

  MYSTRUCT _M2 = {0,0};


解决方案

第一个是最简单的(涉及较少键入的),它是保证工作,所有成员都将被设置为 0 [参考1] 。结果
二是更具可读性。

选择取决于用户的preference或您的编码标准的任务之一。

[参考1] 参考C99标准6.7.8.21:


  

如果有一个大括号括起来的列表更少的初始化值多于使用比在数组中的元素来初始化已知大小的数组元素或聚集的成员,或者更少的字符的字符串,则剩余合计应初始化隐含一样具有静态存储持续时间的对象。


良好阅读:结果
<一href=\"http://stackoverflow.com/questions/10828294/c-and-c-partial-initialization-of-automatic-structure\">C和C ++:自动结构的部分初始化

If I have a struct like this:

typedef struct
{
    unsigned char c1;
    unsigned char c2;
} myStruct;

What would be the easiest way to initialize this struct to 0? Would the following suffice?

myStruct _m1 = {0};

or Would I need to explicitly init each member to 0?

myStruct _m2 = {0,0};

解决方案

The first is easiest(involves less typing), and it is guaranteed to work, all members will be set to 0[Ref 1].
The second is more readable.

The choice depends on user preference or the one which your coding standard mandates.

[Ref 1] Reference C99 Standard 6.7.8.21:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Good Read:
C and C++ : Partial initialization of automatic structure

这篇关于初始化一个结构为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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