在 C 中没有参数的 printf() 编译得很好.如何? [英] printf() with no arguments in C compiles fine. how?

查看:90
本文介绍了在 C 中没有参数的 printf() 编译得很好.如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了下面的 c 程序 &我希望得到编译时错误,但为什么编译器没有给出任何错误?

I tried the below c program & I expected to get compile time error, but why compiler isn't giving any error?

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

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

Why output is compiler dependent? Here is the output on various compilers

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

Output on Orwell Dev C++ IDE (uses gcc 4.8.1) : 0

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

Output on Visual C++ provided by Visual Studio 2010 : 0

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

CodeBlocks IDE (uses gcc 4.7.1) : garbage value

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

Online compiler ideone.com : garbage value

这里出了什么问题?

推荐答案

您的程序将可以正常编译,因为 printf() 是一个可变参数函数,并且使用提供的格式说明符的数量进行匹配检查默认情况下不执行参数.

Your program will compile fine, as printf() is a variadic function and the matching check of the number of format specifiers with supplied argument is not performed by default.

在运行时,您的程序表现出未定义行为,因为没有提供必须使用提供的格式说明符打印.

At runtime, your program exhibits undefined behaviour, as there in no argument supplied which has to be printed using the supplied format specifier.

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

As per chapter 7.19.6.1, c99 standard, (from fprintf())

如果格式的参数不足,则行为是未定义.

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

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

If you compile using -Wformat flag in gcc, your compiler will produce the warning for the mismatch.

这篇关于在 C 中没有参数的 printf() 编译得很好.如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆