How to ensure structures are completly initialized (by name) in GCC?
- by Steven Spark
How do I ensure each and every field of my structures are initialized in GCC when using designated initializers? (I'm especially interested in function pointers.) (I'm using C not C++.)
Here is an example:
typedef struct {
int a;
int b;
} foo_t;
typedef struct {
void (*Start)(void);
void (*Stop)(void);
} bar_t;
foo_t fooo = {
5
};
foo_t food = {
.b=4
};
bar_t baro = {
NULL
};
bar_t bard = {
.Start = NULL
};
-Wmissing-field-initializers does not help at all. It works for fooo only in GCC (mingw 4.7.3, 4.8.1), and clang does only marginally better (no warnings for food and bard).
I'm sure there is a reason for not producing warnings for designated initializer (even when I explicitly ask for them) but I want/need them. I do not want to initialize structures based on order/position because that is more error prone (for example swapping Start and Stop won't even give any warning). And neither gcc nor clang will give any warning that I failed to explicitly initialize a field (when initializing by name). I also don't want to litter my code with if(x.y==NULL) lines for multiple reasons, one of which is I want compile time warnings and not runtime errors.
At least splint will give me warnings on all 4 cases, but unfortunately I cannot use splint all the time (it chokes on some of the code (fails to parse some C99, GCC extensions)).
Note: If I'm using a real function instead of NULL GCC will also show a warning for baro (but not bard).
I searched google and stack overflow but only found related questions and have not found answer for this specific problem.
The best match I have found is 'Ensure that all elements in a structure are initialized'
Ensure that all elements in a structure are initialized
Which asks pretty much the same question, but has no satisfying answer.
Is there a better way dealing with this that I have not mentioned?
(Maybe other code analysis tool? Preferably something (free) that can be integrated into Eclipse or Visual Studio...)