Just see the below program,
#include <stdio.h>
int main()
{
printf("hai");
while(1);
}
The above code is not printing hai and its just waitinG. But if I add
printf("hai\n");
its working.
Can I know what happening internally?
Just see the below program,
#include <stdio.h>
int main()
{
printf("hai");
while(1);
}
The above code is not printing hai and its just waitinG. But if I add
printf("hai\n");
its working.
Can I know what happening internally?
Writing printf("hai\n");
instead will cause, due to the newline character, the output buffer to be flushed, so you'll see the output before entering the infinite loop. There are other ways of flushing the output buffer, but appending the newline character is particularly simple.
Technically the behaviour of a tight loop like while(1);
is undefined in C, but that is unlikely to be the cause of your problem.
printf("hai");
won't show something immediateley, you need to flush stdout
's buffer with either printf("\n");
or fflush(stdout);
Your standart output stream (stdout) is buffered, so it will only flush (and display what is in it) when it is either manually forced or when it recieves a newline character ('\n'
).
You can change this behavior with the library function setbuf()
You can also manually flush the buffer (force it to immideatly display whats currently in it) by using fflush(stdout);