Question

I came across a function today in a C++ file that included a #define macro.
The function ends with a return statement, which is followed by a #undef macro.
An example would be...

int test() {
    #define STUFF()...

    return 0;
    #undef STUFF
}

Is this good or bad practice, and is there any advantage or disadvantage to doing this, or does the #undef need to be located before the return to be acknowledged?

Was it helpful?

Solution

Doing that is just fine, besides, the macro name may clash with another macro name. Hence you may use a ridiculous short name like 'A' or ridiculous long name like 'LIBRARY_LIBRARY_NAME_TEMPORARY_MACRO'

You should place the #undef right after the usage of the maco.

OTHER TIPS

The #define and #undef are compiler directives. They are part of the preprocessing of the code and are ran independent of where they are put in relation of the "real" code.

Basically, before the compiler run your code it goes through every directive (#include, #define, #ifdef) and preprocesses your code, so, for example, when you do:

int firstVariable = MY_DIRECTIVE;
#define MY_DIRECTIVE 7
int doesNothing = 9;

int myVariable = MY_DIRECTIVE;
#undef MY_DIRECTIVE
int thirdVariable = MY_DIRECTIVE;

it transforms it in:

int firstVariable = MY_DIRECTIVE;

int doesNothing = 9;

int myVariable = 7;

int thirdVariable = MY_DIRECTIVE;

And only after it will compile your code (in this case giving you a error that MY_DIRECTIVE hadn't been defined on line 1 and 7)

For more info: Preprocessor directives (cplusplus)

I would not call putting the content of a function by #defined akin to 'best practise'. As @IanMedeiros has indicated it is a pre-compiler directive which means when the compiler runs it has already been expanded. Its difficult to understand what the original author was thinking, but I would would consider a clearer approach which documents more of the authors reasoning with something like:

int test() {
   #if defined(INCLUDE_STUFF)
   Stuff()
   #endif
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top