I am learning conversion specifier part of the C language. I know that %d works for printing value behind commas but, I don't understand why printf
prints something when there are no values behind comma. There are also no compile errors.
#include <stdio.h>
int main(void) {
printf("%d");
return 0;
}
result : 13242433
Can anyone tell me why this randomly numeral appears when I run this code?
Undefined behavior.(Check ref-1, ref-2)
From standard 7.21.6.1
The
fprintf
function writes output to the stream pointed to bystream
, under control of the string pointed to byformat
that specifies how subsequent arguments are converted for output.If there are insufficient arguments for the format, the behavior is undefined
Also when compiled with
gcc -Wall -Wextra -Werror progname.c
gives the error (due to -Werror
)
error: format ‘%d’ expects a matching ‘int’ argument [-Werror=format=]
printf("%d");
^
This was clear enough to tell you what is going wrong. But you didn't check.
it is most likely that the printf
when sees the %d
specifier tries to read one int
variable's value from memory. But alas that memory don't contain anything meaningful to you. (Even accessing that memory might not be permitted.) And yes it's just some value - garbage value. Don't even think that everytime you will get some garbage value - don't rely on it or anything similar. It's undefined behavior. Next time it may crash your program or simply print my contact number.1,2
1. This last part of the answer explains the possible reason for that garbage print.
2. print my contact number
- is simply pointing out that it is just a garbage value which you shouldn't care about. Moreover it's undefined behavior - seeing even a garbage value is not something that is guaranteed to happen every single time.