Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

printf() with no arguments in C compiles fine. how?

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
");
    return 0;
}

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

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

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

CodeBlocks IDE (uses gcc 4.7.1) : garbage value

Online compiler ideone.com : garbage value

What is going wrong here ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...