#define Printf() 字符串中的预处理器替换

#define Pre-processor Replacement in Printf() String

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

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); 
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 作为输出。

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

下面的语句将 THIRTY 替换为 30

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

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