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

前端 未结 10 1956
后悔当初
后悔当初 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 00:52

    what warnings/messages did you get using your compilers? i ran this through gcc (Ubuntu 4.8.2-19ubuntu1) and got a warning

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

    and running it also "garbage output". here, the gcc is so clever to parse the format expression and notifies the coder to provide a matching number of arguments.

    what i think happens: the function signature of printf is independent from the behaviour of the compiled code. at compile time, all the compiler cares is to check if at least one argument is there and continues. however, the compiled function will first parse the format expression and, dependent on that, read further arguments from the functions' arguments stack. therein it simply expects appropriately put values (int, float etc) and uses them. so if you dont specify the argument, no place on the function call stack is reserved and printf still reads random memory (in this case at the first location). this also explains the "garbage" output, which will differ each time you call the binary. you can even extend the code to

    #include 
    int main(void)
    {
        printf("%d\n%d\n");
        return 0;
    }
    

    and get two different garbage numbers :)

    then again it will depend on the environment/process/compiler which values will be read. "unspecified behaviour" is what describes this effect best, sometimes zero, sometimes other.

    i hope this clarifies your issue!

提交回复
热议问题