Behavior of "printf("%d");"

88 Views Asked by At
int main(){
    // Comment the next line, Garbage value is printed. However, this shows an integer value. 
    int x=32;
    printf("%d");
    return 0;
}

Any reason for this behaviour, or is it random??

2

There are 2 best solutions below

0
On BEST ANSWER

You told printf() how to print something (the format specifier %d), but you did not tell printf() what to print.

To elaborate, you forgot to supply the required argument for the supplied format specifier %d.

C standard says, if there are insufficient argument for supplied format specifier, the behaviour is undefined.

FWIW, just specifying the format specifier won't magically consider the argument for it. You need to write something like

 printf("%d", x);

to print the value of x.

1
On

The printf() has the below prototype

int printf(const char *,...);

What you pass is %d to the printf() and since this is a format specifier to print out int printf() looks for the parameter which needs to be printed out since you don't pass any this is undefined behavior