printf 中的宏变量替换

Macro variable substitution in printf

我用一条 printf 语句写了一个简单的程序,比如 hello world。

#include <stdio.h>
#define MAX 100
int main()
{
    printf("Max is %d\n",MAX);
}

我研究过预处理器只是用宏代替了出现的地方。一般 printf 需要一个带有相应格式说明符的变量名来打印变量的值。 在这里,根据我的理解,100 应该在 printf 调用中被替换并且应该引发错误。

但输出是:

Max is 100

如何以及为什么?

"Generally printf() need a variable name with corresponding format specifier to print the value of variable."

你错了。 printf() 提供的所有格式说明符都需要特定类型的 参数 ,而不是 该类型的变量100integer literal,在本例中是 %d 的有效参数。

因此,printf("Max is %d\n",100);C中既是有效的又是合法的陈述。你得到的输出是预期的输出,应该没有错误或警告。

只是为了添加对实际单词的引用,引用 C11,章节 §7.21.6.1,fprintf()(强调我的)

d,i

The int argument is converted to [...]

printf 格式 "%d" 告诉 printf 从参数列表中提取一个 int 参数。如果 int 来自变量或文字,则无关紧要。