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?
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 } };
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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With