what is the difference between struct {0} and memset 0 [duplicate]

Assume we have struct like this:

struct A
{
    int x;
    int y;
};

what is the difference between

A a = {0};

and

A a;
memset(&a,0,sizeof(A));

None. The final outcome is that both initialize structure members to 0.

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.

Your structure A is an aggregate and above rule applies to it. So all the structure members are initialized with value same as for static storage duration. Which is 0.

C99 Standard 7.21.6.1 The memset function:

void *memset(void *s, int c, size_t n);

The memset function copies the value of c (converted to an unsigned char) into each of the first n characters of the object pointed to by s.

In simple words all the members including the alignment/padding bits in object of your structure A are set to 0.

Note that only difference between the two constructs in C is that memset sets the alignment/padding to 0 as well, while the aggregate initialization only guarantees that your structure members are set to 0.

In either case you do not have access to the alignment/padding bytes through convention language constructs and hence both get you the same effect.


Both are setting memory to 0

The first is used to set only a static allocation memory to 0

A a ={0}; // set a staic memory to 0

And you could not do it in this way:

A *a = malloc(sizeof(A)); a = {0} // This could not be done

The second is used to set both dynamic and static allocation memory to 0

A a;
memset(&a,0,sizeof(A));

And you could do also

A *a = malloc(sizeof(A)); memset(a,0,sizeof(A));

Another thing

when using memset to set your memory to 0, here your are calling a function (and this take time). And when setting with {0}, you are not calling a function. So the {0} could be faster than memset