Initialize struct members to 0 (gcc -Wextra)

NiegodziwyBeru picture NiegodziwyBeru · Nov 5, 2012 · Viewed 9.5k times · Source

I want to initialize all struct members to 0. Common solution is to make something like this:

struct foo bar = {0}

I create this example:

#include <stdio.h>

struct Stru2 {
    int c;
    int d;
};

struct Stru1 {
    int a;
    Stru2 b;
};

int main()
{
    struct Stru1 aaa = { 0 };
    return aaa.b.c;
}

And I compile (gcc 4.6.3) it whit this parameters, to make sure how ANSI handle this

gcc -Wall -Wextra -pedantic -ansi main.cpp

And I got following warnings:

main.cpp: In function ‘int main()’: 
main.cpp:36:28: warning: missing initializer for member ‘Stru1::b’ [-Wmissing-field-initializers]

The question is, why -Wextra, generate this warning? Maybe not always "= {0}", set all members to 0?

Answer

Carl Norum picture Carl Norum · Nov 5, 2012

It's just a nanny warning.. = {0} definitely sets all of the members to zero. The reason it's included as a warning at all is for the case where you might add a field to a structure and you want to make sure it gets initialized correctly. Having the warning lets you find those places quickly and fix them. For example, let's say you fix have an initializer something like:

struct Stru1 aaa = { 1, { 2, 3 } };

Now, add a field int e to Stru2:

struct Stru2 {
    int c;
    int d;
    int e;
};

And let's pretend it's very important that e get initialized. Well, without -Wmissing-field-initializers, you'd have to hunt around in your code to find every place you care about. With the warning, you get a diagnostic message like the one you saw, and you can find and fix them very easily:

struct Stru1 aaa = { 1, { 2, 3, 4 } };

To get the advantage of this warning, you do have to go through and fully initialize all of your structures, though. In your case, that means something like:

struct Stru1 aaa = { 0, { 0, 0 } };