Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize struct members to 0 (gcc -Wextra)

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?

like image 545
NiegodziwyBeru Avatar asked Nov 05 '12 19:11

NiegodziwyBeru


2 Answers

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 } };
like image 175
Carl Norum Avatar answered Oct 10 '22 12:10

Carl Norum


Yes, {0} sets all struct members to 0, because it sets the first member to 0, and all other members are by default set to 0 as long as at least one member is initialized. See Are uninitialized struct members always set to zero?.

like image 23
1'' Avatar answered Oct 10 '22 10:10

1''