C中是否允许使用空宏定义?他们的行为如何? [英] Are empty macro definitions allowed in C? How do they behave?
问题描述
假设空宏定义
#define FOO
标准C是否有效?如果是这样,在此定义之后 FOO
是什么?
Is it valid Standard C? If so, what is FOO
after this definition?
推荐答案
是只是一个扩展到什么都没有的宏。但是,既然已经定义了宏,则可以使用 #if defined
(或 #ifdef
)检查宏是否具有
It is simply a macro that expands to, well, nothing. However, now that the macro has been defined you can check with #if defined
(or #ifdef
) whether it has been defined.
#define FOO
int main(){
FOO FOO FOO
printf("Hello world");
}
将扩展为
int main(){
printf("Hello world");
}
在某些情况下,这非常方便,例如其他调试信息,您不想在发行版本中显示:
There are certain situations where this comes in very handy, for example additional debug information, which you don't want to show in your release version:
/* Defined only during debug compilations: */
#define CONFIG_USE_DEBUG_MESSAGES
#ifdef CONFIG_USE_DEBUG_MESSAGES
#define DEBUG_MSG(x) print(x)
#else
#define DEBUG_MSG(x) do {} while(0)
#endif
int main(){
DEBUG_MSG("Entering main");
/* ... */
}
由于宏 CONFIG_USE_DEBUG_MESSAGES
已定义, DEBUG_MSG(x)
将扩展为 print(x)
,您将得到输入main
。如果删除 #define
,则 DEBUG_MSG(x)
会扩展为空的 do
-而
循环时,您不会看到该消息。
Since the macro CONFIG_USE_DEBUG_MESSAGES
has been defined, DEBUG_MSG(x)
will expand to print(x)
and you will get Entering main
. If you remove the #define
, DEBUG_MSG(x)
expands to an empty do
-while
loop and you won't see the message.
这篇关于C中是否允许使用空宏定义?他们的行为如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!