Reputation:
I was trying something when I saw this strange behavior. Can someone please explain it to me.
#include<stdio.h>
int main()
{
printf("utkarsh");
sleep(10);
printf("dixit");
}
The expected output is print "utkarsh" then wait for 10 seconds, print "dixit" next to it. But what I observed was that it waits for 10 seconds and the prints "utkarshdixit".
If I add a \n at end of utkarsh, it works as expected.
printf("utkarsh\n");
Could someone help me understand why am I seeing such behavior ?
Upvotes: 0
Views: 418
Reputation: 647
There is buffering in stdout stream. Hence you need to flush once before sleep.
But when you used a '\n', the c run-time automatically flushes the stdout buffer for you. Hence you see this behaviour
Upvotes: 1
Reputation: 143795
Here, try this
#include<stdio.h>
int main()
{
printf("utkarsh");
fflush(stdout);
sleep(10);
printf("dixit");
}
There's buffering of the standard out going on. you have to explicitly flush it.
Upvotes: 2
Reputation: 1809
printf
is buffering until you decide to write a '\n'
.
You can use : flush
to force to print
Upvotes: 2
Reputation: 1314
you're encoutering buffering.
try to do
fflush(stdout);
in front of the sleep
Upvotes: 5