There are only three cases when output is sent from the buffer to the screen:
1: It is sent when the buffer gets full.
2: When a newline character is encountered (in a line buffered terminal).
3: When there is impending input.
Unlike from what has been said by @Mogzol in the comments, if there was some buffering problem going out here then this simple single loop wouldn't have worked either:
for(i=0;i<47966;i++)
{
printf(" %d",i);
}
There is something else happening in this, step by step example:
CASE 1:
#include<stdio.h>
int main(void)
{
unsigned long int i=47966ull,k;
for(k=0;k<i;++k)
{
}
return 0;
}
This above code takes nearly negligible time to complete, although nothing is done by the loop.
CASE 2:
#include<stdio.h>
int main(void)
{
unsigned long int i=47966,k;
for(i=0;i<47966;i++)
for(k=0;k<47966;++k)
{
}
return 0;
}
This above code nearly takes 9.1 seconds (not counting the error) to run while doing nothing.
CASE 3:
#include<stdio.h>
int main(void)
{
unsigned long int i=47966,k,z;
for(i=0;i<47966;i++)
{
printf(" %d",i);
for(k=0;k<47966;++k)
{
}
}
return 0;
}
This certainly works as from case 1 we can say that for each i
the waiting time is less, hence the digits get printed soon.
Even to print this simple underlying code (you can try that), it takes a massive amount of time:
//WRITTEN TO CHECK WHEN DOES THE FIRST OVERFLOW OCCURS
#include<stdio.h>
int main(void)
{
unsigned long int i=47966,k,z;
for(i=0;i<47966;i++)
{
printf(" %d",i);
for(k=0;k<47966;++k)
{
printf("-");
}
}
return 0;
}
In the case of yours, its a massive waiting time before the first buffer overflow occurs. I have mentioned overflow because:
- Even your terminal is set to line buffer there is no
\n
to flush it.
- There is no impending input.
SOURCE(S):
- What is it with printf() sending output to buffer?
NOTE: Ignore the unsigned long
part - it was just from some old program I didn't bother to change.
MAJOR--> If you use fflush(stdout)
in the inner most loop, you'll find that it is just timing issue - consuming lots of time to buffer all of them from 0 to 47966 as there would be only one number in the buffer between two consecutive flush.