Do I need to execute undef macros inside a function?

I have seen code like this many times:

void func(){ #define a ... ... #undef a } 

Is #undef required at #undef ?

+4
source share
4 answers

This is not necessary, but the scope of #define is global after the specified line. It will not obey the scope of the function if you think it will be.

+11
source

It's not needed. If a macro is intended to be used only inside a function, it is probably a good idea for #undef . If you do not, this means that the macro remains visible through the rest of the translation unit (source file).

Most macros are probably intended to be visible in any source file, so usually the question does not arise.

+3
source

It depends. This is only necessary if you want a not to be potentially available at subsequent points in your program, depending on your logic. define now global (in the current translation block)!

From gnu.org :

If a macro ceases to be useful, it may be undefined with the `#undef 'directive.

Besides,

Once a macro has been undefined, this identifier can be redefined as a macro using the following #define directive. The new definition does not necessarily have some resemblance to the old definition.

and

However, if the identifier, which is currently a macro, is redefined, then the new definition should be essentially the same as the old one. Two macro definitions are actually the same if:

  • Both are the same type of macro (object or function).
  • All notes in the list of tokens match.
  • If there are any parameters, they are the same.
  • Spaces are displayed in the same places in both. It does not have to be the exact same amount of spaces. Remember that comments are considered a space.
+1
source

When I declare a macro, as you did inside the function body, I would #undef this at the end. Because, most likely, it is intended only for this body of function.

In general, the #undef macro is always good when you know that the macro definition will not be used at any time later, because the macro definition applies to all other files that include the macro file.

+1
source

All Articles