Reputation: 1
say I have the following
#define STR(x) #x
#define ONE 1
#define TWO 2
typedef struct
{
int item;
char * name;
}bag_t;
bag_t my_bag[] =
{
{ONE, ""};
{TWO, ""};
}
I want to add the name of the macro to the name variable so something like this:
my_bag[1].name = STR(my_bag[1].item);
That obviously doesn't work since it not expanded. How can workaround this?
Upvotes: 0
Views: 84
Reputation: 399833
Not sure if this is 100% what you want, but perhaps it's close enough:
#define ONE 1
#define TWO 2
typedef struct
{
int item;
const char *name;
}bag_t;
#define BAG_INIT(n) { n, #n }
const bag_t my_bag[] =
{
BAG_INIT(ONE),
BAG_INIT(TWO),
};
int main(void) {
printf("name of %d is '%s'\n", my_bag[0].item, my_bag[0].name);
return 0;
}
This prints:
name of 1 is 'ONE'
Upvotes: 2