Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unusual behaviour with printf with infinite while loop

When I run the below program, I do not get any output.

#include <stdio.h>

int main()
{
    printf("hello");
    while(1)
    {

    }   
    return 0;
}

whereas if i edit the printf command to add a '\n' character to the end of the string, then the expected output comes. what is going on in the first code? I simply cannot understand it.

like image 499
DesirePRG Avatar asked Oct 09 '13 11:10

DesirePRG


1 Answers

This is because stdout is line buffered, i.e. the output is not written to the device (the terminal) until a full line has been collected.

You can call fflush(stdout); to force a flush of the buffer to the terminal. Do not try to flushing stdin by the way, that's not allowed.

like image 119
unwind Avatar answered Sep 20 '22 12:09

unwind