One way to address this problem is using the X Macro concept link1, link 2.
The list of struct members would be
#define LIST_OF_STRUCT_MEMBERS \
X(a) \
X(b) \
X(c)
Then one would declare the struct as:
#define X(name) int name;
struct myStruct {
LIST_OF_STRUCT_MEMBERS
}
#undef X
Where int
could be replaced by any basic data type.
One could then create a const variable initialized to the default value:
#define X(name) -1,
const struct myStruct myStruct_DEFAULT_VALUE = { LIST_OF_STRUCT_MEMBERS };
#undef X
Translated by the preprocessor into:
const struct myStruct myStruct_DEFAULT_VALUE = {-1, -1, -1,};
This can be copied every time a new variable has to be initialized.
The method can easily be verified defining in the same way a print function:
#define X(name) printf("%s = %d\n", #name, in->name);
void printAllMembers(struct myStruct* in) {
LIST_OF_STRUCT_MEMBERS
}
#undef X
(The printAllMembers function might need some modification when the underlying basic data type is changed).
Verified here.
This concept can generalize to a struct with fields of different data types if we include the data type in LIST_OF_STRUCT_MEMBERS
, e.g.:
#define LIST_OF_STRUCT_MEMBERS \
X(int, a) \
X(float, b) \
X(double, c)
#define X(type, name) type name;
struct myStruct {
LIST_OF_STRUCT_MEMBERS
};
#undef X
#define X(type, name) -1,
const struct myStruct myStruct_DEFAULT_VALUE = { LIST_OF_STRUCT_MEMBERS };
#undef X
#define intFormatting "%d"
#define floatFormatting "%f"
#define doubleFormatting "%f"
#define X(type, name) printf(#name " = " type ## Formatting "\n", in->name);
void printMyStruct (struct myStruct* in) {
LIST_OF_STRUCT_MEMBERS
}
#undef X
Tested here.