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

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

问题描述

如果我有这样的结构:

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

将此结构初始化为 0 的最简单方法是什么?以下就够了吗?

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

myStruct _m1 = {0};

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

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

myStruct _m2 = {0,0};

推荐答案

第一个最简单(打字少),保证有效,所有成员都设置为0[Ref 1].
第二个更具可读性.

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] 参考 C99 标准 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.

好书:
C 和 C++:自动结构的部分初始化

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

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