简体   繁体   English

是否有必要在 function 中取消定义宏?

[英]Is it necessary to undef macros within function?

I've seen many times code like this:我见过很多次这样的代码:

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

Is the #undef necessary at all? #undef有必要吗?

It is not necessary, but the scope of a #define is global after the line it was defined.这不是必需的,但#define的 scope 在定义的行之后是全局的。 It will not obey the function scope, if you are thinking it will.它不会服从 function scope,如果你认为它会。

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.如果该宏仅用于 function 内部,则#undef可能是个好主意。 If you don't, that just means that the macro remains visible through the rest of the translation unit (source file).如果你不这样做,那只是意味着宏通过翻译单元(源文件)的 rest 仍然可见。

Most macros are probably intended to be visible throughout a source file anyway, so usually the question doesn't arise.无论如何,大多数宏可能都打算在整个源文件中可见,因此通常不会出现问题。

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.仅当您想确保a根据您的逻辑在程序的稍后时间点可能不可用时,才需要这样做。 The define is now global (in the current translation unit)! define现在是全局的(在当前的翻译单元中)!

From gnu.org :来自gnu.org

If a macro ceases to be useful, it may be undefined with the `#undef' directive.如果一个宏不再有用,它可能用 `#undef' 指令未定义。

Additionally,此外,

Once a macro has been undefined, that identifier may be redefined as a macro by a subsequent `#define' directive.一旦一个宏未被定义,该标识符可以通过后续的“#define”指令重新定义为一个宏。 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.请记住,注释算作空白。

When i declare a macro like you did inside the body of a function then i would #undef it at the end.当我像你在 function 的主体内声明一个宏时,最后我会#undef 它。 Because most probably it is meant for that function body only.因为很可能它仅适用于 function 主体。

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.通常,当您知道宏定义不会在以后任何时候使用时, #undef宏总是一个好主意,因为宏定义会传播到包括具有宏的文件的所有其他文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM