While trying to debug some C code I noticed that a printf() won't execute if placed before an infinite loop. Does anyone know why this is? Practically it's not that big of a deal, but for debugging it's a nightmare.
#include<stdio.h>
int main()
{
int data;
printf("This prints fine.\n");
printf("Enter data: ");
scanf("%d", &data);
printf("This should print but it doesn't.\n");
while(1)
{
//Infinite Loop
}
return 0;
}
On calling printf() , output is displayed after program terminates or newline character is encountered.
But since you are calling infinite loop after printf() , program doesn't terminate and output from buffer is not displayed.
Use fflush(stdout)
to force output from buffer to be displayed
stdout
The standard output stream is the default destination of output for applications. In most systems, it is usually directed by default to the text console (generally, on the screen).
The fflush()
function causes the system to empty the buffer
try __fpurge(stdout) It will clear your output buffer
Their is a concept called line buffer and block buffer. Every thing what you want to write to the screen will be in buffer. line buffer means when ever new line [\n] found it"ll flush the buffer that means your string will print on the screen. block buffer means their will be fixed size for block until unless that block full it"ll not print on the screen. in the above case new line [\n] is enough to print