I am trying to apply the X Macro concept, in order to have the possibility to initialize all struct members to a custom default (invalid) value. I write the following code:
#define LIST_OF_STRUCT_MEMBERS_foo \
X(a) \
X(b) \
X(c)
#define X(name) int name;
struct foo {
LIST_OF_STRUCT_MEMBERS_foo
};
#undef X
#define X(name) -1,
static inline void foo_invalidate(struct foo* in) {
*in = (struct foo){
LIST_OF_STRUCT_MEMBERS_foo
};
}
#undef X
#define X(name) -1,
#define foo_DEFAULT_VALUE { LIST_OF_STRUCT_MEMBERS_foo }
#undef X
static struct foo test = foo_DEFAULT_VALUE;
However, when I run the preprocessor, the definition of foo_DEFAULT_VALUE
fails to substitute the X(name)
calls with -1,
Preprocessor output:
struct foo {
int a; int b; int c;
};
static inline void foo_invalidate(struct foo* in) {
*in = (struct foo){
-1, -1, -1, /*Here the substitution worked nicely*/
};
}
static struct foo test = { X(a) X(b) X(c) }; /*Why this substitution failed?*/
I thought C-macros could refer to other macros. Do you know why that substitution fails? Is there any workaround?
I could live with foo_invalidate
, but I am reluctant to give up one step from having a value to be used directly at initialization.