c - printf 是否将前两个赋值作为输入

标签 c

我在某处读到 printf 采用程序前两个赋值的值。任何 可以给出 printf 的数量。全部只取前两个 值。如果程序中给出了更多的赋值,则 printf 将采用垃圾值。

我不这么认为,但它在很多网站上都有,所以只需要确认一下

例如,如果您对 “printf takes first two assignment as input” 进行简单的 Google 搜索,就会有一些网站提供示例面试问题/答案,例如:

Predict the output or error(s) for the following:

main()
{
    int i=400,j=300;
    printf("%d..%d");
}

Answer: 400..300

Explanation: printf takes the values of the first two assignments of the program. Any number of printf's may be given.

All of them take only the first two values. If more number of assignments given in the program,then printf will take garbage values.

这是正确的真实行为吗?还是取决于实现?

您可以找到这样的问答场所,例如:
this puzzle site
this interview question doc

最佳答案

不,这绝对不是真的。

有关上下文,请阅读 C11 7.21.6.3/2:

The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf.

因此,根据标准 C11 7.21.6.1/2:

The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output. If there are insufficient arguments for the format, the behavior is undefined. [...]

(强调我的)

可能发生的情况是,调用 printf() 时可能会从堆栈中提取值。再者,由于行为未定义,任何事情都可能发生,从打印垃圾值或程序崩溃,到在邻居的并行打印机上打印出蛋糕图片(真的,anything)。

除非您的特定实现(特定 CPU 体系结构,具有特定编译器和可能特定操作系统)记录具体情况作为您可以做的事情,不要做

您的拼图网站的“拼图”主要是未定义行为和关于实现定义行为的错误假设的组合。有些例子是正确的,但考虑到它大多是坏的,我只是假装我从未见过它。随机访问的 Internet 站点往往不是学习编程的好资源,尤其是 C。如果你想学习 C,你应该买一本关于 C 编程的书(列表 can be found here)。

关于c - printf 是否将前两个赋值作为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14342737/

相关文章:

字符指针和空间搜索

c - 字母表的嵌套循环

相当于 fork 的克隆?

c - c中分配给函数参数的最大寄存器数

php - 从网站与现金抽屉通信

c - 打印 float 。 (PowerPC)

c - fwrite() 之后的 fread() 获取 0 个字节

c - 该程序的运行时错误是什么?

c - 多线程或带线程的进程

c - Variadic 函数在 Win32 中有效,但在 Win64 中无效