often I use big struct with more than 20 fields which need to be initialized by different values.
Every time I wrote the init function, I was hypochondriac, that I always worried about I miss one field to be assigned a value. So I had to check each field one by one.
I hate this, So I use a CHECK_VAL macro like sample code.
Now if i miss one item in the struct initialization, the compiler will report an error:
a value of type “Check” cannot be used to initialize an entity of type
“int”
My question: whether there are other way to help my problem? The language is C and C++, and the big struct is POD type.
Code Sample
#define DOCHECK 1
#if DOCHECK
typedef struct _Check{
char k;
} Check;
Check g_check = {'c'};
#define CHECK_DEL Check c1234567;
#define CHECK_VAL (g_check)
#else
#define CHECK_DEL
#define CHECK_VAL
#endif
typedef struct _BigStruct{
int bar;
int foo;
/*...*/
int f99;
int f100;
CHECK_DEL;
}BigStruct;
void initBigStruct(BigStruct* p){
int a,b,c,d;
a = b = c = d = 0;
/*
many other code to caculate the value of a,b,c,d
*/
{
BigStruct tmp = {a,b,c,d, CHECK_VAL};
*p = tmp;
}
}
From a language point of view, probably not a lot.
However, GCC has the
-Wmissing-field-initializersflag for exactly this situation. I’m sure other compilers offer something similar.