开发者

Is it necessary to undef macros within function?

开发者 https://www.devze.com 2023-03-27 10:23 出处:网络
I\'ve seen many t开发者_开发知识库imes code like this: void func(){ #define a ... ... #undef a } Is the #undef necessary at all?It is not necessary, but the scope of a #define is global after the l

I've seen many t开发者_开发知识库imes code like this:

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

Is the #undef necessary at all?


It is not necessary, but the scope of a #define is global after the line it was defined. It will not obey the function scope, if you are thinking it will.


It's not necessary. If the macro is meant to be used only inside the function, it's probably a good idea to #undef it. If you don't, that just means that the macro remains visible through the rest of the translation unit (source file).

Most macros are probably intended to be visible throughout a source file anyway, so usually the question doesn't arise.


When i declare a macro like you did inside the body of a function then i would #undef it at the end. Because most probably it is meant for that function body only.

In general it is always a good idea to #undef a macro when you know that the macro definition is not going to be used anytime later because the macro definition propagate to all other files which include the file having a macro.


That depends. It is only necessary if you want to ensure that a will not be potentially available at later points in your program depending on your logic. The define is now global (in the current translation unit)!

From gnu.org:

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

Additionally,

Once a macro has been undefined, that identifier may be redefined as a macro by a subsequent `#define' directive. The new definition need not have any resemblance to the old definition.

and

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

  • Both are the same type of macro (object- or function-like).
  • All the tokens of the replacement list are the same.
  • If there are any parameters, they are the same.
  • Whitespace appears in the same places in both. It need not be exactly the same amount of whitespace, though. Remember that comments count as whitespace.
0

精彩评论

暂无评论...
验证码 换一张
取 消