jul
13
2010

A brief on “designated initializers”

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 = 0×0}

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

posted in blog by Tiago Maluta

Follow comments via the RSS Feed | Deixe um comentário | Trackback URL

Leave Your Comment