A brief on "designated initializers"

July 13, 2010

[Warning: This post is a backup recovery from my previous Wordpress blog. All content was automatically converted accessing a MySQL database using a Python script (details). Mostly are in Portuguese but if you are interest I can translate to English. If you found any problem dont’t hesitate to contact me in comments.]

The GNU Compiler Collection (GCC) for C language doesn't initialize variables zeroed. For simple variables types like int or float is just equal to 0 or 0.0 respectively. Now, suppose that you have a "large" struct and doesn't want to set each member individually... you could just type "={0}" which means that the first member is explicitly initialized to zero and the remaining members are implicitly initialized, also zero. Let's see an example:

typedef struct { int a; char c; char s[10]; int *ptr; } data;

When you initialize with:

data d;

You got some random value like:

{a = -1208298748, c = -12 ‘\364’, s = “\317\372\267\230\353\377\277\351\203\004”, ptr = 0xb7e94cc5}

When you type:

data d = {0};

You’ll have each struct member initialized to zero.

{a = 0, c = 0 ‘\000’, s = “\000\000\000\000\000\000\000\000\000”, ptr = 0x0}

You can learn much more about designated inits [section 6.26] on GCC docs.