问题描述
#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");
在此, #ifdef
和 #ifndef
,输出是什么?
In this what is the role of #ifdef
and #ifndef
, and what's the output?
推荐答案
里面的文本 ifdef / endif
或 ifndef / endif
pair 将被保留或删除。预处理器取决于条件。 ifdef
表示如果定义了以下内容,而 ifndef
表示如果以下内容不是
Text inside an ifdef/endif
or ifndef/endif
pair will be left in or removed by the pre-processor depending on the condition. ifdef
means "if the following is defined" while ifndef
means "if the following is not defined".
因此:
#define one 0
#ifdef one
printf("one is defined ");
#endif
#ifndef one
printf("one is not defined ");
#endif
等同于:
printf("one is defined ");
因为定义了一个
,所以 ifdef
为true, ifndef
为false。定义为 并不重要。类似的代码段(在我看来更好)是:
since one
is defined so the ifdef
is true and the ifndef
is false. It doesn't matter what it's defined as. A similar (better in my opinion) piece of code to that would be:
#define one 0
#ifdef one
printf("one is defined ");
#else
printf("one is not defined ");
#endif
因为在这种特殊情况下可以更清楚地说明意图。
since that specifies the intent more clearly in this particular situation.
在您的特定情况下, ifdef
之后的文本不会被删除,因为 one
被定义。出于相同的原因,删除了 ifndef
之后的文本。在某个时候需要有两个结束的 endif
行,第一个将导致重新开始包含行,如下所示:
In your particular case, the text after the ifdef
is not removed since one
is defined. The text after the ifndef
is removed for the same reason. There will need to be two closing endif
lines at some point and the first will cause lines to start being included again, as follows:
#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和#ifndef的作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!