In a header outside of my control, there is this:
typedef union {
char * v_charp;
int v_int;
float v_float;
} value_t;
typedef struct var {
char *name;
value_t value;
} variable;
#define VARIABLE_DEF(Name, Value) {Name, {(char*)Value}}
They expect that in my code I’ll do something like this:
variable my_variables[2] = {
VARIABLE_DEF("Variable 1", 1),
VARIABLE_DEF("Variable 2", 2)
};
Whoever wrote this apparently didn’t consider that you might want to initialise the union with a floating-point literal. So I need to figure out how to convert a literal float to an integer of the same bit-pattern. If I could use an intermediate variable then it’d be easy:
float tmp;
variable my_variables[2] = {
VARIABLE_DEF("Variable 1", tmp = 1.1f, *((unsigned int *)(&tmp))),
VARIABLE_DEF("Variable 2", tmp = 2.2f, *((unsigned int *)(&tmp)))
};
But you can’t use variables in struct initialisers. What else can I do?
How about
(Untested)
On second thought, how about defining a more flexible alternative to
VARIABLE_DEFand using that when needed?Something like
should work.
Or just skip the macro:
— is that actually the macro, or are you simplifying a much more complicated case for this discussion?