In C, sometimes my output will not get printed to Terminal until I print the newline character \n
. For example:
int main()
{
printf("Hello, World");
printf("\n");
return 0;
}
The Hello World will not get printed until the next printf
(I know this from setting a breakpoint in gdb). Can someone please explain why this happens and how to get around it?
Thanks!
This is done for performance reasons: passing data to console is too expensive (in terms of execution speed) to do it character-by-character. That is why the output is buffered until the newline is printed: characters are collected in an array until it is time to print, at which time the entire string is passed to the console. You can also force output explicitly, like this:
fflush(stdout);
Additionally to fflush()
you can set the buffering options with setvbuf(3).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With