我用一个 printf
语句编写了一个简单的程序,例如 hello world。
#include <stdio.h>
#define MAX 100
int main()
{
printf("Max is %d\n",MAX);
}
我研究发现宏只是由预处理器替换出现的地方。一般来说,printf
需要一个带有相应格式说明符的变量名来打印变量的值。
在这里,根据我的理解,应该在 printf
调用中替换 100 并且应该引发错误。
但是输出是:
Max is 100
如何以及为什么?
最佳答案
"Generally
printf()
need a variable name with corresponding format specifier to print the value of variable."
你错了。 printf()
提供的所有格式说明符都需要特定类型的参数,而不是变量 属于那种类型。 100
,一个 integer literal ,在本例中是 %d
的有效参数。
因此,printf("Max is %d\n",100);
是 C
中有效且合法的语句。您得到的输出是预期的输出,不应有错误或警告。
只是添加对实际单词的引用,引用 C11
,第 §7.21.6.1 章,fprintf()
(强调我的)
d,i
The int argument is converted to [...]
关于c - printf 中的宏变量替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32439930/