Printf before delay doesn't work in C

Does anyone know why, if I put printf just before the delay, it waits until the delay ends before it displays a message?

Code1 with a dream ():

int main (void) { printf ("hi world"); system("sleep 3"); } 

Code2 with delayed startup:

 void delay(float sec) { time_t start; time_t current; time(&start); do{ time(&current); }while(difftime(current,start) < sec); } int main (void) { printf ("hi world"); delay(3); } 

And if:

 printf ("hi world"); delay(3); printf ("hi world"); delay(3); 

he waits until the amount is asleep, and then he will print messages at the same time.

Why is this happening?

UPDATE: I caused the delay ("sleep 3"), when I called the delay, I meant the delay (3). Fixed

+4
source share
5 answers

standard output is not flush until you output the '\ n' char.

try printf ("hi world \ n");

+9
source

printf buffers its output until a new line is output.

Add fflush (stdout); to flush buffers on demand.

+19
source

Typically, standard output is buffered until you do:

  • print the \n character
  • fflush(stdout) call fflush(stdout)

Do one of these actions before calling delay() , and you should see your output.

+7
source

When you call printf, you don’t print anything until you really need it: until the buffer is full, or you add a new line. Or you explicitly clean it.

So you can either do

 printf("Something\n"); delay(); 

or

 printf("Something"); fflush(stdout); delay(); 
0
source

Technically, this should not even compile. In the delay("sleep 3") call, you are trying to convert const char * to float . It should be:

 void delay (float sec) { // ... } delay(3); 
-one
source

All Articles