Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this line of C do?

Tags:

c

I was just reading about a library called sofia-sip and this line appeared in a code sample:

msg_iovec_t iovec[2] = {{ 0 }};

For reference, here is the definition of msg_iovec_t:

struct iovec {
    void *iov_base;     // Pointer to data.
    size_t iov_len;     // Length of data.
};
like image 286
bloudermilk Avatar asked Mar 20 '11 11:03

bloudermilk


2 Answers

This creates an array of two iovec structures on the stack and initializes all members of both array elements to zero.

The initializer {{ 0 }} only gives an explicit value for the first member of the first array element: iovec[0].iov_base. The supplied value 0 is converted implicitly to a null pointer.

The other members of the first array element and the other array elements are also initialized, implicitly: pointers to null and arithmetic types to 0.

The line can be written equivalently as

msg_iovec_t iovec[2] = { 0 };

This is the shortest standard way to zero-initialize an entire object, so it is idiomatic. Some compilers might accept an empty initializer list {} as an extension. Some compilers might issue a warning for this form and require enough braces to designate the first non-aggregate member (two pairs as in the original line).

The effect is similar to

msg_iovec_t iovec[2];
bzero(iovec, sizeof iovec);

except cleaner and portable, because a pointer filled with zero bytes is not necessarily a null pointer.

like image 124
aaz Avatar answered Sep 22 '22 23:09

aaz


First bracket declares that array is being initialized. The second declares that structure's iovec first field: iov_base is being initialized by NULL value

like image 24
Dewfy Avatar answered Sep 21 '22 23:09

Dewfy