0

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?

Prasath
  • 47
  • 7
  • What's "*nd*", please? – alk Apr 08 '16 at 06:59
  • 1
    [The `stdout` stream is buffered, so will only display what's in the buffer after it reaches a newline (or when it's told to)](http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin). – Joels Elf Apr 08 '16 at 07:00
  • You could alternatively use `fflush(stdout);`. See [here](http://www.cplusplus.com/reference/cstdio/fflush/). – RhinoDevel Apr 08 '16 at 07:02
  • By the way, the program is not waiting (as you wrote) at `while(1);`, it is infinitely looping. If you want the application to wait for a certain time, you can use `sleep()` or `usleep()`, if you want to wait for a key pressed, use something like `getchar()`. – RhinoDevel Apr 08 '16 at 07:09

3 Answers3

0

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.

Bathsheba
  • 220,365
  • 33
  • 331
  • 451
0

printf("hai"); won't show something immediateley, you need to flush stdout's buffer with either printf("\n"); or fflush(stdout);

jdarthenay
  • 2,907
  • 1
  • 12
  • 18
0

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);

user308386
  • 7,069
  • 9
  • 36
  • 50