The most generic way to initialise an automatic variable to zero
(as it would be if in static scope) is to use:
type_t variable = {0,};
This operation is defined by C90, and works whether the variable is
a scalar or aggregate type as demonstrated below.
This can replace memset(&var,0,sizeof(var)) which assumes that
initialised variables are always represented by 0 in static scope
(Not a terrible assumption TBH).
Note the code below along with the assembly generated by gcc-4.1.2 shows that if any element values are not specified, they're initialised as is any unused padding space between elements of aggregate types. However if all elements are explicitly initialised the padding is left untouched.
void f(void)
{
typedef int opaque_t;
opaque_t o = { 0, }; /* can init scalar types like this */
typedef struct { char c; int a; int b; } s_t;
s_t s1 = { 0, };
/* movl $0, -16(%ebp)
movl $0, -12(%ebp)
movl $0, -8(%ebp) */
s_t s2 = { 0, 0, 0 };
/* movb $0, -28(%ebp)
movl $0, -24(%ebp)
movl $0, -20(%ebp) */
s_t s3 = { 1, 0, };
/* movl $0, -52(%ebp)
movl $0, -48(%ebp)
movl $0, -44(%ebp)
movb $1, -52(%ebp) */
}
Unfortunately the gcc -Wmissing-field-initializers option (which is
included in -Wextra) issues a warning for this useful construct,
even when you specify a trailing ',' which should be enough to indicate
one hasn't inadvertantly forgotten some initialisers. I've requested that
this warning should be suppressed when a trailing ',' is specified.
© Sep 23 2008