Initializing a struct to 0

Daan Timmer picture Daan Timmer · Jun 22, 2012 · Viewed 168.2k times · Source

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

Alok Save picture Alok Save · Jun 22, 2012

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