How write macro to avoid redefine?

thinkerou

I have the follow macro:

#define my_add_property(ret, name, value) \
  object tmp; \
  tmp = *value; \
  add_property(ret, 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!

slugonamission

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 a do {} while(0), for example:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related