Is there a way to protect a macro definition? To be more specific consider the following:
#define macro1 x // code segment 1 involving macro1 goes here // code segment 2 involving macro1 goes here // code segment 3 involving macro1 goes here In the example I have placed 3 comments denoting code segments involving the macro. What I would like to do now is to be able to avoid having the macro affect code segment 2. Is there a way to tell the compiler to replace all instances of macro1 in segment 1 and segment 3 but not in segment 2? Here is a possible way:
#define macro1 x // code segment 1 involving macro1 goes here #undef macro1 // code segment 2 involving macro1 goes here #define macro1 x // code segment 3 involving macro1 goes here The drawback is that I have to define the macro again. Say I wanted to use the word NULL in my program (don't ask me why just go with it). I want this to be a variable but the C preprocessor will change it to 0 in most cases. So what I want to do, is to be able to block it for just a short time period and then let it be what it was before.
Failed Attempt:
Let us suppose that macro1 has been defined somewhere externally and we do not even know what the value of such macro is. All we want is to avoid having it replace things in the second segment.
// code segment 1 involving macro1 goes here #ifdef macro1 #define TEMP macro1 #undef macro1 #endif // code segment 2 involving macro1 goes here #ifdef TEMP #define macro1 TEMP #undef TEMP #endif // code segment 3 involving macro1 goes here The idea is to check if the macro exists, if it does, then we want to store the value into another variable, undefine the macro and finally define the macro again when we need it. Unfortunately, this code doesn't work because before we execute code segment 3 macro1 will be replaced by TEMP, not the value that TEMP was supposed to have.