Trying out another example from KandR, I have the following C code:
#include <stdio.h>
int main(){
double nc = 5;
printf("%*.0f",nc);
return 0;
}
This prints 5 and then it keeps moving (printing blank characters) from left to right and then a newline until stopped by pressing Ctrl + C). When I change the printf
line to printf("%.0f",nc)
it works as expected i.e. it just prints 5 and stops.
According to http://www.cplusplus.com/reference/cstdio/printf/ printf's syntax is:
%[flags][width][.precision][length] specifier.
I changed the [width]
to *
so that printf
does not limit the digits in the output.
1) Why does it keep printing blank characters until stopped?
2) When I do not give any width, what does
printf
assume by default?3) I also modified the above code to set
nc = 500
, thenprintf
does not print anything except the continuous blank characters!
When I change it to 500.00, it prints 500 and after that it keeps printing blank characters until stopped. Why is there no output when I set nc=500
and why is there an output when I set nc=500.00
?
The format specifier "%*.0f"
expects two arguments: one is width specifier and the another is for double. Since you pass only one, it invokes undefined behaviour.
If you correct it, for example:
printf("%*.0f",5, nc); // width 5
It'll work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With