Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf continuously printing

Tags:

c

printf

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, then printf 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?

like image 501
user720694 Avatar asked Mar 20 '23 08:03

user720694


1 Answers

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.

like image 91
P.P Avatar answered Apr 06 '23 00:04

P.P