1

After commenting Line 2 "Hello" is printed nine times but commenting Line 1 outputs "Hello" more than nine times. My question is what's the role of '\n' in this?

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int tmp[10], i, n=0;

    for(i=0;i<9;i++)
    {
        tmp[i]=fork();
        if(tmp[i]>0)
            break;
        else
        {
            printf("Hello\n");  //      ---- Line 1
            printf("Hello ");   //      ---- Line 2
        }
    }
}
Bharat Kul Ratan
  • 933
  • 2
  • 11
  • 22
  • 3
    i don't believe the problem is caused by '\n' – jondinham Oct 31 '12 at 06:05
  • Possible duplicate of [Statement before fork() printing twice](http://stackoverflow.com/questions/10700192/statement-before-fork-printing-twice). Different code, but the same issue. – AnT Oct 31 '12 at 06:21

2 Answers2

2

\n also flushes the standard output buffer. If it is not present, it is possible that you have previously entered data in it. Flushing also means it forces printf to print on the screen as soon as \n is processed. Otherwise it is buffered output and you can never predict how long would OS buffer your output and when precisely it chooses to actually print.

fkl
  • 5,068
  • 3
  • 24
  • 66
2

You might be a victim of buffer flush not happening. '\n' at the end of the string makes the output buffer flush. If the output buffer is not flushed, then you might get some output from the previous printf call as well. So it is always better to use a '\n' at the end of a printing string to make sure we flush the buffer. You can look at this question.

Community
  • 1
  • 1
CCoder
  • 2,195
  • 15
  • 37