0

I have a do loop, which schematically looks like this

int iterations = 0 ;

do {
    iterations += 1 ;
    printf("iterations\t%d\n", iterations) ;
    somefunction(does something) ;
} while (some condition) ;

printf("done iterating\n") ;

When I use the format iterations\t%d\n" (line terminated with \n), for each iteration the iteration number is printed to stdout (which in this case is the terminal screen). When instead I use "iterations\t%d\t" (terminated with \t) the iteration number for each iteration is only printed to standard out once I reach the line printf("done iterating\n").

My question is: do I always need to terminate a string with "\n" to print to stdout? I'm confused as my understanding is that when I print to file using fprintf("\n"), I do not need to use any "\n" at the end of the string I am printing to file with for fprintf("") to successfully print to file.

physics_researcher
  • 638
  • 2
  • 9
  • 22
  • Of course you don't. `'\n'` means "new line". Do you _always_ need a new line? Definitely not. For example, this comment doesn't have a new line. – ForceBru Mar 02 '18 at 15:03

1 Answers1

4

stdout is buffered. It saves on the write system call - that is expensive. It involves a context switch between user space and kernel space.

So to speed things up - it is buffered and only written when a new line is encountered

Alternatively use fflush(stdout).

user2736738
  • 30,591
  • 5
  • 42
  • 56
Ed Heal
  • 59,252
  • 17
  • 87
  • 127