#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");在这方面,#ifdef和#ifndef的作用是什么,输出是什么?
发布于 2010-09-19 13:25:07
预处理器将根据情况保留或删除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为true而ifndef为false。它被定义为什么并不重要。一个类似(在我看来更好)的代码片段是:
#define one 0
#ifdef one
printf("one is defined ");
#else
printf("one is not defined ");
#endif因为在这种特定的情况下,这更清楚地指定了意图。
在您的特定情况下,由于定义了one,因此不会删除ifdef后面的文本。出于同样的原因,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发布于 2010-09-19 20:12:52
有人应该提到,在这个问题中有一个小陷阱。#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发布于 2015-09-02 20:58:09
"#if one“意味着如果"#define one”已经被写入,"#if one“被执行,否则"#ifndef one”将被执行。
这只是C语言中if,then,else分支语句的C预处理器(CPP)指令的等价物。
也就是说,如果{#define one} then printf(“一个求值为真");否则printf("one is not defined ");所以如果没有#define one语句,那么将执行该语句的else分支。
https://stackoverflow.com/questions/3744608
复制相似问题