Why use trailing newlines instead of leading with printf?











up vote
50
down vote

favorite
9












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("Initializingn");
init();
printf("Processingn");
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.










share|improve this question




















  • 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






  • 32




    The last line would merge with the command prompt on linux without a trailing newline.
    – GrandmasterB
    2 days ago






  • 3




    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
    2 days ago






  • 5




    Do init() and process_data() print anything themselves? What would you expect the result to look like if they did?
    – Bergi
    2 days ago








  • 4




    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
    yesterday















up vote
50
down vote

favorite
9












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("Initializingn");
init();
printf("Processingn");
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.










share|improve this question




















  • 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






  • 32




    The last line would merge with the command prompt on linux without a trailing newline.
    – GrandmasterB
    2 days ago






  • 3




    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
    2 days ago






  • 5




    Do init() and process_data() print anything themselves? What would you expect the result to look like if they did?
    – Bergi
    2 days ago








  • 4




    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
    yesterday













up vote
50
down vote

favorite
9









up vote
50
down vote

favorite
9






9





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("Initializingn");
init();
printf("Processingn");
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.










share|improve this question















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("Initializingn");
init();
printf("Processingn");
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.







c






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 10 hours ago

























asked Nov 19 at 7:10









Broman

387311




387311








  • 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






  • 32




    The last line would merge with the command prompt on linux without a trailing newline.
    – GrandmasterB
    2 days ago






  • 3




    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
    2 days ago






  • 5




    Do init() and process_data() print anything themselves? What would you expect the result to look like if they did?
    – Bergi
    2 days ago








  • 4




    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
    yesterday














  • 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






  • 32




    The last line would merge with the command prompt on linux without a trailing newline.
    – GrandmasterB
    2 days ago






  • 3




    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
    2 days ago






  • 5




    Do init() and process_data() print anything themselves? What would you expect the result to look like if they did?
    – Bergi
    2 days ago








  • 4




    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
    yesterday








5




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




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




32




32




The last line would merge with the command prompt on linux without a trailing newline.
– GrandmasterB
2 days ago




The last line would merge with the command prompt on linux without a trailing newline.
– GrandmasterB
2 days ago




3




3




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
2 days ago




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
2 days ago




5




5




Do init() and process_data() print anything themselves? What would you expect the result to look like if they did?
– Bergi
2 days ago






Do init() and process_data() print anything themselves? What would you expect the result to look like if they did?
– Bergi
2 days ago






4




4




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
yesterday




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
yesterday










8 Answers
8






active

oldest

votes

















up vote
172
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.






share|improve this answer

















  • 16




    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
    2 days ago








  • 21




    @ErikEidt Note that you should use fprintf(STDERR, …) instead, which is generally not buffered at all for diagnostic output.
    – Deduplicator
    2 days ago






  • 2




    @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
    2 days ago








  • 44




    @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
    2 days ago






  • 18




    @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
    2 days ago




















up vote
49
down vote













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.






share|improve this answer



















  • 18




    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
    2 days ago






  • 23




    POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
    – pipe
    2 days ago








  • 5




    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
    2 days ago






  • 3




    @Baldrickk Right. I have updated my answer to be more affirmative, now.
    – cmaster
    2 days ago










  • C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
    – R..
    13 hours ago


















up vote
19
down vote













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.






share|improve this answer



















  • 1




    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
    8 hours ago




















up vote
15
down vote













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).






share|improve this answer

















  • 13




    Yes, "okn" is much better than "nok"...
    – cmaster
    2 days ago




















up vote
14
down vote













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.






share|improve this answer










New contributor




alephzero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


















  • 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
    yesterday


















up vote
6
down vote














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("Initializingn");//Write a line
printf("Processingn"); //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
"Processingn");





share|improve this answer























  • 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
    8 hours ago












  • @TobySpeight Here's a round toit. Look forward to trying your re-improved ispell.el.
    – chux
    8 hours ago


















up vote
2
down vote













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.






share|improve this answer

















  • 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
    16 hours ago










  • 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
    15 hours ago


















up vote
2
down vote













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.






share|improve this answer





















    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "131"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: false,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f381711%2fwhy-use-trailing-newlines-instead-of-leading-with-printf%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown




















    StackExchange.ready(function () {
    $("#show-editor-button input, #show-editor-button button").click(function () {
    var showEditor = function() {
    $("#show-editor-button").hide();
    $("#post-form").removeClass("dno");
    StackExchange.editor.finallyInit();
    };

    var useFancy = $(this).data('confirm-use-fancy');
    if(useFancy == 'True') {
    var popupTitle = $(this).data('confirm-fancy-title');
    var popupBody = $(this).data('confirm-fancy-body');
    var popupAccept = $(this).data('confirm-fancy-accept-button');

    $(this).loadPopup({
    url: '/post/self-answer-popup',
    loaded: function(popup) {
    var pTitle = $(popup).find('h2');
    var pBody = $(popup).find('.popup-body');
    var pSubmit = $(popup).find('.popup-submit');

    pTitle.text(popupTitle);
    pBody.html(popupBody);
    pSubmit.val(popupAccept).click(showEditor);
    }
    })
    } else{
    var confirmText = $(this).data('confirm-text');
    if (confirmText ? confirm(confirmText) : true) {
    showEditor();
    }
    }
    });
    });






    8 Answers
    8






    active

    oldest

    votes








    8 Answers
    8






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    172
    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.






    share|improve this answer

















    • 16




      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
      2 days ago








    • 21




      @ErikEidt Note that you should use fprintf(STDERR, …) instead, which is generally not buffered at all for diagnostic output.
      – Deduplicator
      2 days ago






    • 2




      @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
      2 days ago








    • 44




      @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
      2 days ago






    • 18




      @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
      2 days ago

















    up vote
    172
    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.






    share|improve this answer

















    • 16




      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
      2 days ago








    • 21




      @ErikEidt Note that you should use fprintf(STDERR, …) instead, which is generally not buffered at all for diagnostic output.
      – Deduplicator
      2 days ago






    • 2




      @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
      2 days ago








    • 44




      @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
      2 days ago






    • 18




      @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
      2 days ago















    up vote
    172
    down vote



    accepted







    up vote
    172
    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.






    share|improve this answer












    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.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 19 at 7:17









    Kilian Foth

    87k33235262




    87k33235262








    • 16




      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
      2 days ago








    • 21




      @ErikEidt Note that you should use fprintf(STDERR, …) instead, which is generally not buffered at all for diagnostic output.
      – Deduplicator
      2 days ago






    • 2




      @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
      2 days ago








    • 44




      @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
      2 days ago






    • 18




      @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
      2 days ago
















    • 16




      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
      2 days ago








    • 21




      @ErikEidt Note that you should use fprintf(STDERR, …) instead, which is generally not buffered at all for diagnostic output.
      – Deduplicator
      2 days ago






    • 2




      @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
      2 days ago








    • 44




      @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
      2 days ago






    • 18




      @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
      2 days ago










    16




    16




    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
    2 days ago






    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
    2 days ago






    21




    21




    @ErikEidt Note that you should use fprintf(STDERR, …) instead, which is generally not buffered at all for diagnostic output.
    – Deduplicator
    2 days ago




    @ErikEidt Note that you should use fprintf(STDERR, …) instead, which is generally not buffered at all for diagnostic output.
    – Deduplicator
    2 days ago




    2




    2




    @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
    2 days ago






    @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
    2 days ago






    44




    44




    @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
    2 days ago




    @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
    2 days ago




    18




    18




    @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
    2 days ago






    @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
    2 days ago














    up vote
    49
    down vote













    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.






    share|improve this answer



















    • 18




      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
      2 days ago






    • 23




      POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
      – pipe
      2 days ago








    • 5




      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
      2 days ago






    • 3




      @Baldrickk Right. I have updated my answer to be more affirmative, now.
      – cmaster
      2 days ago










    • C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
      – R..
      13 hours ago















    up vote
    49
    down vote













    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.






    share|improve this answer



















    • 18




      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
      2 days ago






    • 23




      POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
      – pipe
      2 days ago








    • 5




      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
      2 days ago






    • 3




      @Baldrickk Right. I have updated my answer to be more affirmative, now.
      – cmaster
      2 days ago










    • C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
      – R..
      13 hours ago













    up vote
    49
    down vote










    up vote
    49
    down vote









    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.






    share|improve this answer














    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.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 2 days ago

























    answered 2 days ago









    cmaster

    6,06311220




    6,06311220








    • 18




      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
      2 days ago






    • 23




      POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
      – pipe
      2 days ago








    • 5




      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
      2 days ago






    • 3




      @Baldrickk Right. I have updated my answer to be more affirmative, now.
      – cmaster
      2 days ago










    • C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
      – R..
      13 hours ago














    • 18




      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
      2 days ago






    • 23




      POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
      – pipe
      2 days ago








    • 5




      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
      2 days ago






    • 3




      @Baldrickk Right. I have updated my answer to be more affirmative, now.
      – cmaster
      2 days ago










    • C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
      – R..
      13 hours ago








    18




    18




    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
    2 days ago




    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
    2 days ago




    23




    23




    POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
    – pipe
    2 days ago






    POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
    – pipe
    2 days ago






    5




    5




    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
    2 days ago




    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
    2 days ago




    3




    3




    @Baldrickk Right. I have updated my answer to be more affirmative, now.
    – cmaster
    2 days ago




    @Baldrickk Right. I have updated my answer to be more affirmative, now.
    – cmaster
    2 days ago












    C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
    – R..
    13 hours ago




    C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
    – R..
    13 hours ago










    up vote
    19
    down vote













    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.






    share|improve this answer



















    • 1




      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
      8 hours ago

















    up vote
    19
    down vote













    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.






    share|improve this answer



















    • 1




      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
      8 hours ago















    up vote
    19
    down vote










    up vote
    19
    down vote









    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.






    share|improve this answer














    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.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 2 days ago

























    answered 2 days ago









    The Guy with The Hat

    328110




    328110








    • 1




      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
      8 hours ago
















    • 1




      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
      8 hours ago










    1




    1




    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
    8 hours ago






    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
    8 hours ago












    up vote
    15
    down vote













    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).






    share|improve this answer

















    • 13




      Yes, "okn" is much better than "nok"...
      – cmaster
      2 days ago

















    up vote
    15
    down vote













    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).






    share|improve this answer

















    • 13




      Yes, "okn" is much better than "nok"...
      – cmaster
      2 days ago















    up vote
    15
    down vote










    up vote
    15
    down vote









    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).






    share|improve this answer












    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).







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 2 days ago









    Alex Vong

    32913




    32913








    • 13




      Yes, "okn" is much better than "nok"...
      – cmaster
      2 days ago
















    • 13




      Yes, "okn" is much better than "nok"...
      – cmaster
      2 days ago










    13




    13




    Yes, "okn" is much better than "nok"...
    – cmaster
    2 days ago






    Yes, "okn" is much better than "nok"...
    – cmaster
    2 days ago












    up vote
    14
    down vote













    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.






    share|improve this answer










    New contributor




    alephzero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.


















    • 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
      yesterday















    up vote
    14
    down vote













    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.






    share|improve this answer










    New contributor




    alephzero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.


















    • 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
      yesterday













    up vote
    14
    down vote










    up vote
    14
    down vote









    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.






    share|improve this answer










    New contributor




    alephzero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.









    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.







    share|improve this answer










    New contributor




    alephzero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.









    share|improve this answer



    share|improve this answer








    edited 2 days ago





















    New contributor




    alephzero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.









    answered 2 days ago









    alephzero

    24925




    24925




    New contributor




    alephzero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





    New contributor





    alephzero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






    alephzero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.












    • 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
      yesterday


















    • 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
      yesterday
















    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
    yesterday




    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
    yesterday










    up vote
    6
    down vote














    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("Initializingn");//Write a line
    printf("Processingn"); //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
    "Processingn");





    share|improve this answer























    • 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
      8 hours ago












    • @TobySpeight Here's a round toit. Look forward to trying your re-improved ispell.el.
      – chux
      8 hours ago















    up vote
    6
    down vote














    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("Initializingn");//Write a line
    printf("Processingn"); //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
    "Processingn");





    share|improve this answer























    • 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
      8 hours ago












    • @TobySpeight Here's a round toit. Look forward to trying your re-improved ispell.el.
      – chux
      8 hours ago













    up vote
    6
    down vote










    up vote
    6
    down vote










    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("Initializingn");//Write a line
    printf("Processingn"); //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
    "Processingn");





    share|improve this answer















    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("Initializingn");//Write a line
    printf("Processingn"); //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
    "Processingn");






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited yesterday

























    answered yesterday









    chux

    32118




    32118












    • 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
      8 hours ago












    • @TobySpeight Here's a round toit. Look forward to trying your re-improved ispell.el.
      – chux
      8 hours ago


















    • 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
      8 hours ago












    • @TobySpeight Here's a round toit. Look forward to trying your re-improved ispell.el.
      – chux
      8 hours ago
















    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
    8 hours ago






    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
    8 hours ago














    @TobySpeight Here's a round toit. Look forward to trying your re-improved ispell.el.
    – chux
    8 hours ago




    @TobySpeight Here's a round toit. Look forward to trying your re-improved ispell.el.
    – chux
    8 hours ago










    up vote
    2
    down vote













    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.






    share|improve this answer

















    • 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
      16 hours ago










    • 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
      15 hours ago















    up vote
    2
    down vote













    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.






    share|improve this answer

















    • 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
      16 hours ago










    • 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
      15 hours ago













    up vote
    2
    down vote










    up vote
    2
    down vote









    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.






    share|improve this answer












    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.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 2 days ago









    Ian

    4,1611225




    4,1611225








    • 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
      16 hours ago










    • 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
      15 hours ago














    • 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
      16 hours ago










    • 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
      15 hours ago








    1




    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
    16 hours ago




    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
    16 hours ago












    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
    15 hours ago




    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
    15 hours ago










    up vote
    2
    down vote













    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.






    share|improve this answer

























      up vote
      2
      down vote













      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.






      share|improve this answer























        up vote
        2
        down vote










        up vote
        2
        down vote









        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.






        share|improve this answer












        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 8 hours ago









        Toby Speight

        32729




        32729






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f381711%2fwhy-use-trailing-newlines-instead-of-leading-with-printf%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown











            Popular posts from this blog

            Ellipse (mathématiques)

            Quarter-circle Tiles

            Mont Emei