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

前端 未结 10 1969
后悔当初
后悔当初 2020-12-02 00:10

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

#include 
int main(void)
{
          


        
10条回答
  •  感动是毒
    2020-12-02 01:00

    This is simply undefined behavior if you do not provide the sufficient arguments to printf, which mean the behavior is unpredictable. From the draft C99 standard section 7.19.6.1 The fprintf function which also covers printf for this case:

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

    Since printf is a variadic function there is no matching of arguments to the function declaration. So the compiler needs to support support format string checking which is covered by -Wformat flag in gcc:

    Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense. This includes standard functions, and others specified by format attributes (see Function Attributes), [...]

    Enabling sufficient compiler warnings is important, for this code gcc using the -Wall flag tells us (see it live):

     warning: format '%d' expects a matching 'int' argument [-Wformat=]
     printf("%d\n");
     ^
    

提交回复
热议问题