【问题标题】:#define Pre-processor Replacement in Printf() String#define Printf() 字符串中的预处理器替换
【发布时间】:2015-10-08 08:48:39
【问题描述】:

我正在打印一个字符串,例如:

printf("Print the number thirty: 30\n"); 

如果我做出以下定义

#define THIRTY 30

现在

printf("Print the number thirty: THIRTY"); 

C 预处理器是否替换了字符串中的THIRTY --> 30

或者我必须去:

printf("Print then number thirty: %d", THIRTY); 

【问题讨论】:

  • 快点试试怎么样?

标签: c string macros printf c-preprocessor


【解决方案1】:

C 预处理器不理解 String 内部的内容,因此不操作字符串。

以下语句将THIRTY 替换为30

printf("Print then number thirty: %d", THIRTY);  

【讨论】:

    【解决方案2】:

    PreProcessor 可以做到,但你必须对你的定义进行字符串化。

    #define xstr(s) str(s)
    #define str(s) #s
    #define THIRTY 30
    #define TEST "Print the number thirty: " xstr(THIRTY) "\n"
    
    int main()
    {
        printf(TEST);
        return 0;
    }
    

    看看THIS

    【讨论】:

      【解决方案3】:
      printf("Print the number thirty: THIRTY");   // it will consider is whole as a string 
      

      这只会在输出中打印Print the number thirty: THIRTY

      你的第二个陈述 -

      printf("Print then number thirty: %d", THIRTY);  //you probably need this
      

      将打印 - Print then number thirty:30 作为输出。

      【讨论】:

      • @LPs 这不是重点。 OP 想知道哪一个会按他的预期工作。因此,答案是。
      • 问题是C预处理器是否替换了字符串中的THIRTY --> 30? PreProcessor 可以...
      • 预处理器会用那个宏定义来做吗?然后需要更改宏定义。问题在于那个宏定义。所以没有那个定义预处理器不会那样做。
      • @LPs 你的代码中有一些额外的东西,因此它会起作用。但是只有#define THIRTY 30 它不会。我认为问题解决了这个问题。
      • 我猜想,可能我错了,OP 正在寻求一种方法来加快 printf 使用提供预格式化字符串的预处理器方式。这是为了避免 printf 评估 %d 格式。
      猜你喜欢
      • 2015-10-04
      • 2020-06-17
      • 1970-01-01
      • 2022-06-14
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      相关资源
      最近更新 更多