Creating and Initializing structs with variable length macro in C -
i trying create , initialize struct using variable length macro. want able create/initialize struct '0's , initialize fields of struct values optionally passed in.
is possible do? trying following:
#define init_entry(x, ...) \ entry_t x = {.id = 0, .age = 0} \ x.id = <i want use arg1 here> x.age = <i want use arg2 here if exists> is there way accomplish this?
it can done combination of argument counting , concatenation.
first need macro counts it's arguments, i'll call
nargsasked , answered here. note answers compiler-dependent.next need series of macros specific cases:
#define init_entry_0(x) entry_t x = {.id = 0, .age = 0}
#define init_entry_1(x, _id) entry_t x = {.id = _id, .age = 0}
#define init_entry_2(x, _id, _age) entry_t x = {.id = _id, .age = _age}you need concatenation macro:
#define concat(a, b) a##blast, use concatenation choose correct one:
#define init_entry(x, ...) concat(init_entry_, nargs(__va_args__))(x, #__va_args__)
Comments
Post a Comment