Daan Timmer Daan Timmer - 3 years ago 151
C Question

Initializing a struct to 0

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};

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download