thinkerou thinkerou - 4 months ago 18
C Question

How write macro to avoid redefine?

I have the follow macro:

#define my_add_property(return, name, value) \
object tmp; \
tmp = *value; \
add_property(return, name, &tmp);


Now I use the macro in the follow function:

void func() {
object *ret;
my_add_property(ret, "key", my_func1());
my_add_property(ret, "value", my_func2());
}


It will have
make error
:
tmp
is redefined.

So I want to use
object tmp##name
, but if name is
"key"
,
tmp##name
will be
tmp"key"
. I should do how write the macro that make
tmp##name
to
tmpkey
not
tmp"key"
? thanks!

Answer

You can create a new scope inside your macro, such that tmp is only live for a short amount of time by wrapping the implementation in braces, for example:

#define my_add_property(return, name, value) { \
  object tmp;                                  \
  tmp = *value;                                \
  add_property(return, name, &tmp); }