sazr
sazr

Reputation: 25928

Store Preprocessor Constants Value then 'overwrite' through undef/define

I am trying to store a Preprocessor Constant's value then 'overwrite' it.

My Problem: The code below attempts to store a preprocessor constant's value in variable 'A' then the code undefines that variable then redefines it so it has a new value. The problem is that variable 'A' has the newly defined value and not the old one, if that makes sense. Can I store a Preprocessor Constants value and not its reference(Which is what seems like is happening)?

#ifdef CUSTOM_EVENT_CALLBACK_DEFINED
  #define SUB_CUSTOM_EVENT_CALLBACK_DEFINED CUSTOM_EVENT_CALLBACK_DEFINED
  #undef CUSTOM_EVENT_CALLBACK_DEFINED
#endif
#define CUSTOM_EVENT_CALLBACK_DEFINED "def"

int main()
{
    printf(CUSTOM_EVENT_CALLBACK_DEFINED);     // prints out "def". 
    printf("\n");
    printf(SUB_CUSTOM_EVENT_CALLBACK_DEFINED); // prints out "def". I was hoping this would be "abc"
    printf("\n");

    system("PAUSE");
    return 0;
}

// Usage: where the function def is a callback function for a window in a civil engineering program that runs ontop of windows
int def(int id, int cmd, int type)
{
    #ifdef SUB_CUSTOM_EVENT_CALLBACK_DEFINED
      SUB_CUSTOM_EVENT_CALLBACK_DEFINED(id, cmd, type);
    #endif

    // perform my custom code here
}

Upvotes: 1

Views: 1127

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258598

Short answer - no, it's not possible. Macros don't work like that.

But I doubt you really need to do this. A workaround, for example, would be to store the value in a variable before you overwrite it:

#ifdef CUSTOM_EVENT_CALLBACK_DEFINED
  std::string SUB_CUSTOM_EVENT_CALLBACK_DEFINED = CUSTOM_EVENT_CALLBACK_DEFINED;
  #undef CUSTOM_EVENT_CALLBACK_DEFINED
#else
  std::string SUB_CUSTOM_EVENT_CALLBACK_DEFINED = "";
#endif

#define CUSTOM_EVENT_CALLBACK_DEFINED "def"

int main()
{
    printf(CUSTOM_EVENT_CALLBACK_DEFINED);     // prints out "def". 
    printf("\n");
    printf(SUB_CUSTOM_EVENT_CALLBACK_DEFINED); // prints out "def". I was hoping this would be "abc"
    printf("\n");

    system("PAUSE");
    return 0;
}

Or not use macros at all for this purpose.

Upvotes: 2

Related Questions