c - printf 中的宏变量替换

标签 c macros printf c-preprocessor

我用一个 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/

相关文章:

java - 当相同的 printf 方法在控制台上正确打印出来时,如何解决 Eclipse 调试器窗口上的 java printf 问题 ("source not found.")?

c - printf/scanf 系列中的格式 %n 是否有任何实际应用?

c - 这个宏是什么意思?

c++ - 用于 Visual Studio 的零参数参数计数宏

java - 如何在 jni 函数中使用整数和 boolean 值作为输入参数?

c - 好的老初学者 killer : Pointers

c++ - 从过剩教程中了解宏测量数组计数

c - 字符串/数组参数有助于 C 编程

c - 如何在 TM4C123GXL (Tiva) Launchpad 上使用 I2C

c - 在 Ansi-C VS2010 项目中包含 Agilent 驱动程序会导致错误 LNK2001