9

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?

5
  • 2
    This is a little thing that really annoys me. People who do cout << endl << ..; also drives me mad. I know there's no difference but ...
    – Vitor Py
    Commented Jun 28, 2011 at 16:14
  • Do you mean "flushing" in the sense of "new line" or as in fflush()? Commented Jun 28, 2011 at 16:22
  • @Lenny222: in the sense of fflush().
    – peoro
    Commented Jun 28, 2011 at 17:21
  • 1
    Ah, haven't realized, that printf() flushes on newlines, in contrast to C++ streams. Commented Jun 29, 2011 at 7:59
  • Because they are wrong. It is generally a newbie mistake Commented Feb 11, 2016 at 7:32

7 Answers 7

16

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.

4
  • 16
    The difference is if you put it at the start of the line you guarantee that it will print out on a new line. If you're working on a big codebase there may be a line printing out before yours that doesn't have a newline being appended to it. Commented Jun 28, 2011 at 15:37
  • 1
    This is particularly true if you are sticking in print statements for debugging purposes. Commented Jun 28, 2011 at 15:47
  • 3
    Ok, but in this way a new message ("Hello2\n") could end up on the same line of your last one (ending up in "\nHelloHello2\n"): isn't this as bad as having your message on the same line of the previous one (eg: "\nPrevious-messageHello\n")? If these two scenarios are bad in the same way, a programmer/project should adopt a standard (eg: always putting '\n' at the beginning, or at the end), but I can't see what advantages you could have by putting '\n' at the beginning of your messages...
    – peoro
    Commented Jun 29, 2011 at 0:21
  • @peoro, I think my update should offer a solution if it really bothers you.
    – user3792
    Commented Jun 30, 2011 at 13:43
5

Two words: personal preference. In the grand scheme of things, I don't think this really matters. If you're annoyed by it, ask the author of this code why they write it like that. You may get some interesting answers.

I prefer all of my newline characters at the end of each line anyway.

2
  • +1 - It is all preference. I prefer my newline at the end of the string as well because it seems more natural to me
    – Jetti
    Commented Jun 28, 2011 at 15:29
  • 1
    Personally, when I have enough output for this to matter, I try to keep all of the actual printfs, couts and newlines in a single function (perhaps up in main()) so I can prevent any silly bugs related to missing/extra newlines. But maybe I'm just OCD about them.
    – Ixrec
    Commented Mar 1, 2015 at 19:36
4

As someone who uses this idiom in some contexts — although I generally put \n at the end to ensure flushing —, I can offer a justification: I tend to use this when formatting many lines, especially if starting with an empty line, so that the \ns are aligned. This means that it is somewhat easier to (a) check that all lines do indeed include a \n or (b) to ignore them as ballast, and just read the text in the lines. In this situation it actually looks tidier to me, too, but I do find all these benefits minor.

An alternative approach to minimise syntactic ballast is to use string literals including new lines, but 6.4.5 in the C11 standard forbids them, so you have to speak nicely to your compiler and think carefully about what it will do.

2

A reason not mentioned (unless I missed it), is that some CLI programs will use '\r' to repeatedly update a line. For example, with status.

The next line will require a newline to get the cursor to, well, the next (new) line.

Another (very bad) example is where the programmer is aware that multiple programs may be writing to the same terminal. In this chaotic case, there is a chance that some order will be imposed by the leading '\n' flushing out buffered text before writing more and possibly scrambling the outputs of writes. But such ordering is not guaranteed, and sooner or later the other process will barge in and ruin things. Don't do this on anything you'd want to show off to your mom!

I would try to keep the above example to debugging purposes, and not subject users other than yourself to the results. This would apply with multiple unsynchronized tasks writing to the same (hopefully debug) file as well.

The case of using '\r' to write over a line of text on the screen is, however, not that rare in the CLI world.

Stuff happens, after all.

0

Another advantage of having "\n" at the beginning of lines occurs when you want to print some variable values in the x = 5 form.

See how the R code

cat("\n x = ", x)
cat("\n y = ", y)
cat("\n z = ", z)

is shorter than

cat("x = ", x, "\n")
cat("y = ", y, "\n")
cat("z = ", z, "\n")
0

I am one of those '\n at the beginning' people, with a clear reason for it: logging. It is useful to always put a a timestamp at the beginning of the line, followed by some arbitrary amount of other stuff.

So I can always do:

    printf("\n%d ", timestamp);
    print_other_stuff();
    if (something) {
      print_more_stuff();
    }

This approach assures that the timestamp is always at the beginning of the line. I leave it as an exercise for the reader to re-cast that with \n printed at the end of the line.

0

There are two reasonable strategies: Euther print newline always after the last item on the line. Or always before the first item of the next line.

If the last item(s) of a line are often optional then it may be easier to print newlines with the first item of the next line.

Or you explicitly print \n on its own when you want a new line. Takes one extra line but may be easier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.