C Mystery! (GNU/Linux Programming)

This morning, I received a mail from the ILUG-Kochi mailing list to which I’ve subscribed. It was about a mystery in C Programming.

Here is the code:



{printf("Hello World");



We expect the program to print “Hello World”  and then enter the infinite loop. Instead, it enters the infinite loop directly without printing the ‘Hello World” !

The solution also was given in the next mail 🙂

stdout is buffered, meaning it displays the contents of the buffer only after it meets with a ‘newline’ (\n) character.

To print immediately, either use fprintf()< or write().

Another option is to unbuffer the stdout stream:

setbuf(stdout,NULL);  //Now printf() prints immediately without waiting for a '\n'

Else use the

fflush(stdout); //after the printf() command.

Languages are always fun..for me at least since recently 🙂 It’s only when someone points out certain things(like the members of the mailing list did to me:) ), that we find the trick n gimmicks!

(Note: This might not be the same in Turbo and Borland C)

Tagged , , ,

3 thoughts on “C Mystery! (GNU/Linux Programming)

  1. akash viswan says:


  2. akash viswan says:

    but printf will work without \n na,

    • dj says:

      try it buddy…it works if the while(1); infinite loop wasn’t there..since the program enters an infinite loop and does not terminate, we will have to manually force the contents out of the buffer 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: