gpt4 book ai didi

c - 在 C 中没有参数的 printf() 可以正常编译。如何?

转载 作者:太空狗 更新时间:2023-10-29 17:14:35 26 4
gpt4 key购买 nike

我尝试了下面的 c 程序,我预计会出现编译时错误,但为什么编译器没有给出任何错误?

#include <stdio.h>
int main(void)
{
printf("%d\n");
return 0;
}

为什么输出依赖于编译器?这是各种编译器的输出

Orwell Dev C++ IDE(使用 gcc 4.8.1)的输出:0

Visual Studio 2010 提供的 Visual C++ 输出:0

CodeBlocks IDE(使用 gcc 4.7.1):垃圾值

在线编译器ideone.com:垃圾值

这里出了什么问题?

最佳答案

您的程序可以正常编译,因为 printf() 是一个可变参数函数,默认情况下不会执行格式说明符数量与所提供参数的匹配检查。

在运行时,您的程序显示 undefined behaviour ,因为没有提供必须使用提供的格式说明符打印的参数。

根据第 7.19.6.1 章,c99 标准,(来自 fprintf())

If there are insufficient arguments for the format, the behavior is undefined.

如果您在 gcc 中使用 -Wformat 标志进行编译,您的编译器将产生不匹配的警告。

关于c - 在 C 中没有参数的 printf() 可以正常编译。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28194227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com