C Strings – Why Use ‘\n’ at the Beginning?

cstrings

Very often I get into C code where printf format strings start with \n:

printf( "\nHello" );

This in my opinion is an annoying thing that offers no advantages (rather many disadvantages!) with respect to printing "Hello\n":

  • If the first printed line begins with '\n', program output will begin with a (useless) empty line
  • If the last printed line doesn't end with '\n', program output won't end with a new line (useful when reading the output on a terminal)
  • On most terminals (on line buffered streams in general), output gets flushed when a '\n' is encountered, so a line not ending with '\n' could be shown on screen much time after it's been actually printf'd (or maybe never, if the stream never gets flushed, for instance if the program crashes)

So, why do people does like this?

Best Answer

Generally, it is done to ensure that the statement is printed on the next line. If it is done at the end of the line, the same effect can be derived. It really is of little consequence.

Update: As long as you pick one way and stick with it, it really is not going to matter one bit. If you are really concerned then type all your statements as "\nHello\n". If you do have some lines mashing together, then this is really not that hard of a "bug" to fix. Just go back and change the offending statement.

Related Topic