考虑:
#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");
其中,
#ifdef
和#ifndef
的作用是什么,输出是什么?
ifdef/endif
或ifndef/endif
pair内的文本将被预处理器保留或删除,具体取决于条件。 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
为 true,而 ifndef
为 false。它被定义为什么并不重要。一段类似的(我认为更好)代码是:#define one 0
#ifdef one
printf("one is defined ");
#else
printf("one is not defined ");
#endif
因为在这种特定情况下更清楚地说明了意图。
在您的特定情况下,由于定义了
ifdef
,因此不会删除
one
之后的文本。出于同样的原因,删除了
ifndef
之后的文本。在某个时刻需要有两条结束 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
有人应该提到,问题中有一个小陷阱。
#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
“#if one”表示如果写了“#define one”则执行“#if one”,否则执行“#ifndef one”。
即 if {#define one} then printf("one 的计算结果为真值"); 别的 printf("一个未定义"); 因此,如果没有 #define one 语句,则该语句的 else 分支将被执行。
代码看起来很奇怪,因为 printf 不在任何功能块中。