#ifdef和#ifndef的作用

102
#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");

#ifdef#ifndef在这里的作用是什么,输出结果是什么?

4个回答

135

ifdef/endif或者ifndef/endif之间的文本将根据条件被预处理器保留或删除。其中ifdef意味着“如果定义了以下内容”,而ifndef则意味着“如果以下内容未被定义”。

因此:

#define one 0
#ifdef one
    printf("one is defined ");
#endif
#ifndef one
    printf("one is not defined ");
#endif

等同于:

printf("one is defined ");

由于one被定义,因此ifdef为真,ifndef为假。它被定义为什么并不重要。我认为一段类似(甚至更好)的代码如下:

#define one 0
#ifdef one
    printf("one is defined ");
#else
    printf("one is not defined ");
#endif

在这种特定情况下,使用"since that"可以更清楚地表达意图。

对于你的情况,在ifdef之后的文本没有被删除,因为one已经定义了。在ifndef之后的文本因为同样的原因被删除了。最终需要两个closing endif语句,并且第一个语句将导致包含行的开始,如下所示:

     #define one 0
+--- #ifdef one
|    printf("one is defined ");     // Everything in here is included.
| +- #ifndef one
| |  printf("one is not defined "); // Everything in here is excluded.
| |  :
| +- #endif
|    :                              // Everything in here is included again.
+--- #endif

68

有人应该在问题中提到一个小陷阱。 #ifdef 只会检查以下符号是否已通过 #define 或命令行定义,但其值(实际上是其替换)并不重要。 你甚至可以这样写:

#define one

预编译器接受这个。但如果你使用#if,那就是另外一回事了。

#define one 0
#if one
    printf("one evaluates to a truth ");
#endif
#if !one
    printf("one does not evaluate to truth ");
#endif

会给出 one does not evaluate to truth。关键字defined可以获得所需的行为。

#if defined(one) 

因此,它相当于#ifdef

#if结构的优点在于可以更好地处理代码路径,请尝试使用旧的#ifdef/#ifndef对进行类似的操作。

#if defined(ORA_PROC) || defined(__GNUC) && __GNUC_VERSION > 300

0
"

“#if one” 的意思是,如果已经写了“#define one”,则执行“#if one”,否则执行“#ifndef one”。

这只是C语言中if、then、else分支语句的C预处理器(CPP)指令等效物。

例如: if {#define one} then printf("one evaluates to a truth "); else printf("one is not defined "); 因此,如果没有#define one语句,则将执行语句的else分支。

"

4
我不确定这篇回答有什么其他回答没有提到的内容,而且你的例子不是C或C++。 - SirGuy

-2
代码看起来很奇怪,因为printf不在任何函数块中。

1
整个代码块可以放在一个函数内部。欢迎来到stackoverflow,请阅读https://stackoverflow.com/help/how-to-answer。 - rajashekar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接