I heard that you should avoid leading newlines when using printf. So that instead of printf("\nHello World!") you should use printf("Hello World!\n")

In this particular example above it does not make sense, since the output would be different, but consider this:

printf("Initializing");
init();
printf("\nProcessing");
process_data();
printf("\nExiting");

compared to:

printf("Initializing\n");
init();
printf("Processing\n");
process_data();
printf("Exiting");

I cannot see any benefit with trailing newlines, except that it looks better. Is there any other reason?

EDIT:

I'll address the close votes here and now. I don't think this belong to Stack overflow, because this question is mainly about design. I would also say that although it may be opinions to this matter, Kilian Foth's answer and cmaster's answer proves that there are indeed very objective benefits with one approach.

  • 5
    This question is on the border between "issues with code" (which is off-topic) and "conceptual software design" (which is on-topic). It may get closed, but don't take it too hard. I think adding concrete code examples was the right choice nevertheless. – Kilian Foth Nov 19 at 7:20
  • 44
    The last line would merge with the command prompt on linux without a trailing newline. – GrandmasterB Nov 19 at 17:08
  • 4
    If it "looks better" and it has no downside, that's a good enough reason to do it, IMO. Writing good code is no different to writing a good novel or a good technical paper - the devil is always in the detail. – alephzero Nov 19 at 17:20
  • 5
    Do init() and process_data() print anything themselves? What would you expect the result to look like if they did? – Bergi Nov 19 at 19:20
  • 9
    \n is a line terminator, not a line separator. This is evidenced by the fact that text files, on UNIX, almost always end in \n. – Jonathon Reinhart Nov 20 at 18:40
up vote 218 down vote accepted

A fair amount of terminal I/O is line-buffered, so by ending a message with \n you can be certain that it will be displayed in a timely manner. With a leading \n the message may or may not be displayed at once. Often, this would mean that each step displays the progress message of the previous step, which causes no end of confusion and wasted time when you try to understand a program's behaviour.

  • 19
    This is particularly important when using printf for debugging a program that crashes. Putting the newline at the end of a printf means that stdout to the console gets flushed at each printf. (Note that when stdout is redirected to a file, the std libraries will usually do block buffering instead of line buffering, so that makes printf debugging a crash quite hard even with newline at the end.) – Erik Eidt Nov 19 at 14:33
  • 25
    @ErikEidt Note that you should use fprintf(STDERR, …) instead, which is generally not buffered at all for diagnostic output. – Deduplicator Nov 19 at 16:29
  • 4
    @Deduplicator Writing diagnostic messages to the error stream has its downsides as well - many scripts assume a program has failed if something is written to the error stream. – Voo Nov 19 at 16:32
  • 54
    @Voo: I would argue that any program that assumes writes to stderr indicate a failure is itself incorrect. The exit code of the process is what indicates whether or not it failed. If it was a failure, then the stderr output will explain why. If the process exited successfully (exit code zero) then stderr output should be considered informational output for a human user, with no particular machine-parseable semantic (it might contain human-readable warnings, for example), while stdout is the actual output of the program, possibly suitable for further processing. – Daniel Pryden Nov 19 at 16:58
  • 23
    @Voo: What programs are you describing? I'm not aware of any widely-used software package that behaves like you describe. I do know that there are programs that do, but it's not like I just made up the convention I describe above: that's the way the vast majority of programs in a Unix or Unix-like environment work, and to my knowledge, the way the vast majority of programs always have. I certainly wouldn't advocate for any program to avoid writing to stderr simply because some scripts don't handle it well. – Daniel Pryden Nov 19 at 18:05

On POSIX systems (basically any linux, BSD, whatever open-source based system you can find), a line is defined to be a string of characters that's terminated by a newline \n. This is the basic assumption all the standard command line tools build upon, including (but not limited to) wc, grep, sed, awk, and vim. This is also the reason why some editor (like vim) always add a \n at the end of a file, and why earlier standards of C required headers to end with a \n character.

Btw: Having \n terminated lines makes processing of text much easier: You know for sure that you've got a complete line when you've got that terminator. And you know for sure that you need to look at more characters if you didn't encounter that terminator yet.

Of course, this is on the input side of programs, but program output is very often used as program input again. So, your output should stick to the convention for the sake of allowing seamless input into other programs.

  • 25
    This is one of the oldest debates in software engineering: is it better to use newlines (or, in a programming language, another "end of statement" marker like a semicolon) as line terminators or line separators? Both approaches have their pros and cons. The Windows world has mostly settled on the idea that the newline sequence (which is typically CR LF there) is a line separator, and thus the last line in a file doesn't need to end with it. In the Unix world, though, a newline sequence (LF) is a line terminator, and many programs are built around this assumption. – Daniel Pryden Nov 19 at 13:54
  • 33
    POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character." – pipe Nov 19 at 14:52
  • 6
    Given that as @pipe says, it's in the POSIX specification, we can probably call it de jure as opposed to de facto as the answer suggests? – Baldrickk Nov 19 at 16:11
  • 4
    @Baldrickk Right. I have updated my answer to be more affirmative, now. – cmaster Nov 19 at 16:18
  • C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior. – R.. Nov 21 at 18:26

In addition to what other have mentioned, I feel like there is a much simpler reason: it's the standard. Whenever anything prints to STDOUT, it almost always assumes that it is already on a new line, and thus doesn't need to start a new one. It also assumes the next line to be written will act the same way, so it helpfully ends by starting a new line.

If you output leading-newline lines interleaved with standard trailing-newline lines," it will end up looking like this:

Trailing-newline-line
Trailing-newline-line

Leading-newline-line
Leading-newline-line
Leading-newline-lineTrailing-newline-line
Trailing-newline-line

Leading-newline-lineTrailing-newline-line
Trailing-newline-line
Trailing-newline-line

...which is presumably not what you want.

If you use only leading newlines in your code and only run it in an IDE, it may turn out okay. As soon as you run it in a terminal or introduce other people's code that will write to STDOUT alongside your code, you'll see undesirable output like above.

  • 2
    Something similar happens with programs that are interrupted in an interactive shell - if a partial line is printed (missing its newline), then the shell gets confused about which column the cursor is on, making it hard to edit the next command line. Unless you add a leading newline to your $PS1, which would then be an irritant following conventional programs. – Toby Speight Nov 21 at 23:16

Since the highly up-voted answers have already given excellent technical reasons why trailing newlines should be preferred, I will approach it from another angle.

In my opinions, the followings make a program more readable:

  1. a high signal-to-noise ratio (aka simple but not simpler)
  2. important ideas come first

From the above points, we can argue that trailing newlines are better. Newlines are formatting "noise" when compared to the message, the message should stand out and thus should come first (syntax-highlighting can help too).

  • 19
    Yes, "ok\n" is much better than "\nok"... – cmaster Nov 19 at 22:17
  • @cmaster: Reminds me of having read about MacOS using Pascal-string APIs in C, which required prefixing all string literals with a magic escape code like "\pFoobar" . – grawity Nov 23 at 9:46

Using trailing newlines simplifies later modifications.

As a (very trivial) example based on the OP's code, suppose you need to produce some output before the "Initializing" message, and that output comes from a different logical part of the code, in a different source file.

When you run the first test and find "Initializing" is now appended to the end of a line of some other output, you have to search through the code to find where it got printed, and then hope changing "Initializing" to "\nInitializing" doesn't screw up the format of something else, in different circumstances.

Now consider how to are going to handle the fact that your new output is actually optional, so your change to "\nInitializing" sometimes produces an unwanted blank line at the start of the output ...

Do you set a global (shock horror??!!!) flag saying whether there was any preceding output and test it to print "Initializing" with an optional leading "\n", or do you output the "\n" along with your earlier output and leave future code readers wondering why this "Initializing" doesn't have a leading "\n" like all the other output messages do?

If you consistently output trailing newlines, at the point where you know you have reached the end of the line that needs to be terminated, you sidestep all those issues. Note, that might require a separate puts("\n") statement at the end of some logic that outputs a line piece by piece, but the point is you output the newline at the earliest place in the code where you know you need to do it, not somewhere else.

  • 1
    If every independent output item is supposed to appear on its own line, trailing new lines can work fine. If multiple items should be consolidated when practical, however, things get more complicated. If it's practical to feed all output through a common routine, an operation to insert a clear-to-end-of-line if the last character was a CR, nothing if the last character was a newline, and a newline if the last character was anything else, may be helpful if programs need to do something other than output a sequence of independent lines. – supercat Nov 20 at 20:40

Why use trailing newlines instead of leading with printf?

Closely match C spec.

The C library defines a line as ending with a new-line character '\n'.

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. C11 §7.21.2 2

Code that writes data as lines will then match that concept of the library.

printf("Initializing"); // Write part of a line
printf("\nProcessing"); // Finish prior line & write part of a line
printf("\nExiting");    // Finish prior line & write an implementation-defined last line

printf("Initializing\n");//Write a line 
printf("Processing\n");  //Write a line
printf("Exiting");       //Write an implementation-defined last line

Re: last line requires a terminating new-line character. I'd recommend to always write a final '\n' on output and tolerate its absence on input.


Spell checking

My spell checker complains. Perhaps your does too.

  v---------v Not a valid word
"\nProcessing"

 v--------v OK
"Processing\n");
  • I did once improve ispell.el to cope better with that. I admit it was more often \t that was the problem, and it could be avoided simply by breaking the string into multiple tokens, but it was just a side-effect of more general "ignore" work, to selectively skip non-text parts of HTML or MIME multipart bodies, and non-comment parts of code. I did always mean to extend it to switching languages where there's appropriate metadata (e.g. <p lang="de_AT"> or Content-Language: gd), but never did get a Round Tuit. And the maintainer rejected my patch outright. :-( – Toby Speight Nov 21 at 23:28
  • @TobySpeight Here's a round toit. Look forward to trying your re-improved ispell.el. – chux Nov 21 at 23:33

Leading newlines can often make it easier to write the code when there are conditionals, for example,

printf("Initializing");
if (jobName != null)
    printf(": %s", jobName);
init();
printf("\nProcessing");

(But as has been noted elsewhere you may need to flush the output buffer before doing any steps that takes much CPU time.)

Hence a good case can be made for both ways of doing it, however personly I don't like printf() and would use a custom class to build up the output.

  • 1
    Could you explain why this version is easier to write than one with trailing newlines? In this example it is not apparent to me. Instead I could see problems arising with the next output being added to the same line as "\nProcessing". – Raimund Krämer Nov 21 at 15:18
  • Like Raimund, I can also see problems arising from working like this. You need to consider surrounding prints when calling printf. What if you wanted to conditionalize the whole "Initializing" line? You'd have to include the "Procesing" line in that condition to know if you should prefix with a newline or not. If there's another print ahead and you need to conditionalize the "Processing" line, you would also need to include the next print in that condition to know if you should prefix with another newline, and so forth for each print. – JoL Nov 21 at 16:20
  • 2
    I agree with the principle, but the example isn't a good one. A more relevant example would be with code which is supposed to output some number of items per line. If the output is supposed to start with a header that ends with a newline, and each line is supposed to start with a header, it may be easier to say, e.g. if ((addr & 0x0F)==0) printf("\n%08X:", addr); and unconditionally add a newline to the output at the end, than to use separate code for each line's header and the trailing newline. – supercat Nov 23 at 20:23

Leading newlines don't work well with other library functions, notably puts() and perror in the Standard Library, but also any other library you're likely to use.

If you want to print a pre-written line (either a constant, or one already formatted - e.g. with sprintf()), then puts() is the natural (and efficient) choice. However, there's no way for puts() to end the previous line and write an unterminated line - it always writes the line terminator.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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