【问题标题】:The role of #ifdef and #ifndef#ifdef 和 #ifndef 的作用
【发布时间】:2011-04-14 06:18:29
【问题描述】:
#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");

这里面#ifdef#ifndef的作用是什么,输出是什么?

【问题讨论】:

    标签: c-preprocessor


    【解决方案1】:

    ifdef/endififndef/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 为真,ifndef 为假。将它定义为 并不重要。类似(我认为更好)的一段代码是:

    #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
    

    【讨论】:

      【解决方案2】:

      有人应该提到这个问题有一个小陷阱。 #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
      

      【讨论】:

        【解决方案3】:

        “#if one”表示如果已经写入“#define one”,则执行“#if one”,否则执行“#ifndef one”。

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

        即 if {#define one} then printf("one 的计算结果为真"); 别的 printf("未定义一个"); 因此,如果没有#define 一个语句,则将执行该语句的 else 分支。

        【讨论】:

        • 我不确定这增加了其他答案尚未涵盖的内容,而且您的示例不是 C 或 C++。
        【解决方案4】:

        代码看起来很奇怪,因为 printf 不在任何功能块中。

        【讨论】:

        猜你喜欢
        • 2012-12-27
        • 2023-03-28
        • 1970-01-01
        • 2013-02-11
        • 2022-01-20
        • 1970-01-01
        • 1970-01-01
        • 2017-07-25
        相关资源
        最近更新 更多