Why use trailing newlines instead of leading with printf?
up vote
70
down vote
favorite
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
|
show 12 more comments
up vote
70
down vote
favorite
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
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
42
The last line would merge with the command prompt on linux without a trailing newline.
– GrandmasterB
Nov 19 at 17:08
4
If it "looks better" and it has no downside, that's a good enough reason to do it, IMO. Writing good code is no different to writing a good novel or a good technical paper - the devil is always in the detail.
– alephzero
Nov 19 at 17:20
5
Doinit()
andprocess_data()
print anything themselves? What would you expect the result to look like if they did?
– Bergi
Nov 19 at 19:20
7
n
is a line terminator, not a line separator. This is evidenced by the fact that text files, on UNIX, almost always end inn
.
– Jonathon Reinhart
Nov 20 at 18:40
|
show 12 more comments
up vote
70
down vote
favorite
up vote
70
down vote
favorite
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
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
c
edited 12 hours ago
asked Nov 19 at 7:10
Broman
4901311
4901311
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
42
The last line would merge with the command prompt on linux without a trailing newline.
– GrandmasterB
Nov 19 at 17:08
4
If it "looks better" and it has no downside, that's a good enough reason to do it, IMO. Writing good code is no different to writing a good novel or a good technical paper - the devil is always in the detail.
– alephzero
Nov 19 at 17:20
5
Doinit()
andprocess_data()
print anything themselves? What would you expect the result to look like if they did?
– Bergi
Nov 19 at 19:20
7
n
is a line terminator, not a line separator. This is evidenced by the fact that text files, on UNIX, almost always end inn
.
– Jonathon Reinhart
Nov 20 at 18:40
|
show 12 more comments
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
42
The last line would merge with the command prompt on linux without a trailing newline.
– GrandmasterB
Nov 19 at 17:08
4
If it "looks better" and it has no downside, that's a good enough reason to do it, IMO. Writing good code is no different to writing a good novel or a good technical paper - the devil is always in the detail.
– alephzero
Nov 19 at 17:20
5
Doinit()
andprocess_data()
print anything themselves? What would you expect the result to look like if they did?
– Bergi
Nov 19 at 19:20
7
n
is a line terminator, not a line separator. This is evidenced by the fact that text files, on UNIX, almost always end inn
.
– Jonathon Reinhart
Nov 20 at 18:40
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
42
42
The last line would merge with the command prompt on linux without a trailing newline.
– GrandmasterB
Nov 19 at 17:08
The last line would merge with the command prompt on linux without a trailing newline.
– GrandmasterB
Nov 19 at 17:08
4
4
If it "looks better" and it has no downside, that's a good enough reason to do it, IMO. Writing good code is no different to writing a good novel or a good technical paper - the devil is always in the detail.
– alephzero
Nov 19 at 17:20
If it "looks better" and it has no downside, that's a good enough reason to do it, IMO. Writing good code is no different to writing a good novel or a good technical paper - the devil is always in the detail.
– alephzero
Nov 19 at 17:20
5
5
Do
init()
and process_data()
print anything themselves? What would you expect the result to look like if they did?– Bergi
Nov 19 at 19:20
Do
init()
and process_data()
print anything themselves? What would you expect the result to look like if they did?– Bergi
Nov 19 at 19:20
7
7
n
is a line terminator, not a line separator. This is evidenced by the fact that text files, on UNIX, almost always end in n
.– Jonathon Reinhart
Nov 20 at 18:40
n
is a line terminator, not a line separator. This is evidenced by the fact that text files, on UNIX, almost always end in n
.– Jonathon Reinhart
Nov 20 at 18:40
|
show 12 more comments
8 Answers
8
active
oldest
votes
up vote
207
down vote
accepted
A fair amount of terminal I/O is line-buffered, so by ending a message with n you can be certain that it will be displayed in a timely manner. With a leading n the message may or may not be displayed at once. Often, this would mean that each step displays the progress message of the previous step, which causes no end of confusion and wasted time when you try to understand a program's behaviour.
19
This is particularly important when using printf for debugging a program that crashes. Putting the newline at the end of a printf means that stdout to the console gets flushed at each printf. (Note that when stdout is redirected to a file, the std libraries will usually do block buffering instead of line buffering, so that makes printf debugging a crash quite hard even with newline at the end.)
– Erik Eidt
Nov 19 at 14:33
24
@ErikEidt Note that you should usefprintf(STDERR, …)
instead, which is generally not buffered at all for diagnostic output.
– Deduplicator
Nov 19 at 16:29
4
@Deduplicator Writing diagnostic messages to the error stream has its downsides as well - many scripts assume a program has failed if something is written to the error stream.
– Voo
Nov 19 at 16:32
50
@Voo: I would argue that any program that assumes writes to stderr indicate a failure is itself incorrect. The exit code of the process is what indicates whether or not it failed. If it was a failure, then the stderr output will explain why. If the process exited successfully (exit code zero) then stderr output should be considered informational output for a human user, with no particular machine-parseable semantic (it might contain human-readable warnings, for example), while stdout is the actual output of the program, possibly suitable for further processing.
– Daniel Pryden
Nov 19 at 16:58
22
@Voo: What programs are you describing? I'm not aware of any widely-used software package that behaves like you describe. I do know that there are programs that do, but it's not like I just made up the convention I describe above: that's the way the vast majority of programs in a Unix or Unix-like environment work, and to my knowledge, the way the vast majority of programs always have. I certainly wouldn't advocate for any program to avoid writing to stderr simply because some scripts don't handle it well.
– Daniel Pryden
Nov 19 at 18:05
|
show 5 more comments
up vote
66
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.
22
This is one of the oldest debates in software engineering: is it better to use newlines (or, in a programming language, another "end of statement" marker like a semicolon) as line terminators or line separators? Both approaches have their pros and cons. The Windows world has mostly settled on the idea that the newline sequence (which is typically CR LF there) is a line separator, and thus the last line in a file doesn't need to end with it. In the Unix world, though, a newline sequence (LF) is a line terminator, and many programs are built around this assumption.
– Daniel Pryden
Nov 19 at 13:54
29
POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
– pipe
Nov 19 at 14:52
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
Nov 19 at 16:11
3
@Baldrickk Right. I have updated my answer to be more affirmative, now.
– cmaster
Nov 19 at 16:18
C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
– R..
Nov 21 at 18:26
|
show 1 more comment
up vote
28
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.
2
Something similar happens with programs that are interrupted in an interactive shell - if a partial line is printed (missing its newline), then the shell gets confused about which column the cursor is on, making it hard to edit the next command line. Unless you add a leading newline to your$PS1
, which would then be an irritant following conventional programs.
– Toby Speight
Nov 21 at 23:16
add a comment |
up vote
16
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:
- a high signal-to-noise ratio (aka simple but not simpler)
- 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).
17
Yes,"okn"
is much better than"nok"
...
– cmaster
Nov 19 at 22:17
@cmaster: Reminds me of having read about MacOS using Pascal-string APIs in C, which required prefixing all string literals with a magic escape code like"pFoobar"
.
– grawity
yesterday
add a comment |
up vote
15
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.
New contributor
If every independent output item is supposed to appear on its own line, trailing new lines can work fine. If multiple items should be consolidated when practical, however, things get more complicated. If it's practical to feed all output through a common routine, an operation to insert a clear-to-end-of-line if the last character was a CR, nothing if the last character was a newline, and a newline if the last character was anything else, may be helpful if programs need to do something other than output a sequence of independent lines.
– supercat
Nov 20 at 20:40
add a comment |
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");
I did once improveispell.el
to cope better with that. I admit it was more oftent
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">
orContent-Language: gd
), but never did get a Round Tuit. And the maintainer rejected my patch outright. :-(
– Toby Speight
Nov 21 at 23:28
@TobySpeight Here's a round toit. Look forward to trying your re-improvedispell.el
.
– chux
Nov 21 at 23:33
add a comment |
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.
1
Could you explain why this version is easier to write than one with trailing newlines? In this example it is not apparent to me. Instead I could see problems arising with the next output being added to the same line as"nProcessing"
.
– Raimund Krämer
Nov 21 at 15:18
Like Raimund, I can also see problems arising from working like this. You need to consider surrounding prints when callingprintf
. What if you wanted to conditionalize the whole "Initializing" line? You'd have to include the "Procesing" line in that condition to know if you should prefix with a newline or not. If there's another print ahead and you need to conditionalize the "Processing" line, you would also need to include the next print in that condition to know if you should prefix with another newline, and so forth for each print.
– JoL
Nov 21 at 16:20
1
I agree with the principle, but the example isn't a good one. A more relevant example would be with code which is supposed to output some number of items per line. If the output is supposed to start with a header that ends with a newline, and each line is supposed to start with a header, it may be easier to say, e.g.if ((addr & 0x0F)==0) printf("n%08X:", addr);
and unconditionally add a newline to the output at the end, than to use separate code for each line's header and the trailing newline.
– supercat
yesterday
add a comment |
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.
add a comment |
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
207
down vote
accepted
A fair amount of terminal I/O is line-buffered, so by ending a message with n you can be certain that it will be displayed in a timely manner. With a leading n the message may or may not be displayed at once. Often, this would mean that each step displays the progress message of the previous step, which causes no end of confusion and wasted time when you try to understand a program's behaviour.
19
This is particularly important when using printf for debugging a program that crashes. Putting the newline at the end of a printf means that stdout to the console gets flushed at each printf. (Note that when stdout is redirected to a file, the std libraries will usually do block buffering instead of line buffering, so that makes printf debugging a crash quite hard even with newline at the end.)
– Erik Eidt
Nov 19 at 14:33
24
@ErikEidt Note that you should usefprintf(STDERR, …)
instead, which is generally not buffered at all for diagnostic output.
– Deduplicator
Nov 19 at 16:29
4
@Deduplicator Writing diagnostic messages to the error stream has its downsides as well - many scripts assume a program has failed if something is written to the error stream.
– Voo
Nov 19 at 16:32
50
@Voo: I would argue that any program that assumes writes to stderr indicate a failure is itself incorrect. The exit code of the process is what indicates whether or not it failed. If it was a failure, then the stderr output will explain why. If the process exited successfully (exit code zero) then stderr output should be considered informational output for a human user, with no particular machine-parseable semantic (it might contain human-readable warnings, for example), while stdout is the actual output of the program, possibly suitable for further processing.
– Daniel Pryden
Nov 19 at 16:58
22
@Voo: What programs are you describing? I'm not aware of any widely-used software package that behaves like you describe. I do know that there are programs that do, but it's not like I just made up the convention I describe above: that's the way the vast majority of programs in a Unix or Unix-like environment work, and to my knowledge, the way the vast majority of programs always have. I certainly wouldn't advocate for any program to avoid writing to stderr simply because some scripts don't handle it well.
– Daniel Pryden
Nov 19 at 18:05
|
show 5 more comments
up vote
207
down vote
accepted
A fair amount of terminal I/O is line-buffered, so by ending a message with n you can be certain that it will be displayed in a timely manner. With a leading n the message may or may not be displayed at once. Often, this would mean that each step displays the progress message of the previous step, which causes no end of confusion and wasted time when you try to understand a program's behaviour.
19
This is particularly important when using printf for debugging a program that crashes. Putting the newline at the end of a printf means that stdout to the console gets flushed at each printf. (Note that when stdout is redirected to a file, the std libraries will usually do block buffering instead of line buffering, so that makes printf debugging a crash quite hard even with newline at the end.)
– Erik Eidt
Nov 19 at 14:33
24
@ErikEidt Note that you should usefprintf(STDERR, …)
instead, which is generally not buffered at all for diagnostic output.
– Deduplicator
Nov 19 at 16:29
4
@Deduplicator Writing diagnostic messages to the error stream has its downsides as well - many scripts assume a program has failed if something is written to the error stream.
– Voo
Nov 19 at 16:32
50
@Voo: I would argue that any program that assumes writes to stderr indicate a failure is itself incorrect. The exit code of the process is what indicates whether or not it failed. If it was a failure, then the stderr output will explain why. If the process exited successfully (exit code zero) then stderr output should be considered informational output for a human user, with no particular machine-parseable semantic (it might contain human-readable warnings, for example), while stdout is the actual output of the program, possibly suitable for further processing.
– Daniel Pryden
Nov 19 at 16:58
22
@Voo: What programs are you describing? I'm not aware of any widely-used software package that behaves like you describe. I do know that there are programs that do, but it's not like I just made up the convention I describe above: that's the way the vast majority of programs in a Unix or Unix-like environment work, and to my knowledge, the way the vast majority of programs always have. I certainly wouldn't advocate for any program to avoid writing to stderr simply because some scripts don't handle it well.
– Daniel Pryden
Nov 19 at 18:05
|
show 5 more comments
up vote
207
down vote
accepted
up vote
207
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.
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.
answered Nov 19 at 7:17
Kilian Foth
87.3k33235262
87.3k33235262
19
This is particularly important when using printf for debugging a program that crashes. Putting the newline at the end of a printf means that stdout to the console gets flushed at each printf. (Note that when stdout is redirected to a file, the std libraries will usually do block buffering instead of line buffering, so that makes printf debugging a crash quite hard even with newline at the end.)
– Erik Eidt
Nov 19 at 14:33
24
@ErikEidt Note that you should usefprintf(STDERR, …)
instead, which is generally not buffered at all for diagnostic output.
– Deduplicator
Nov 19 at 16:29
4
@Deduplicator Writing diagnostic messages to the error stream has its downsides as well - many scripts assume a program has failed if something is written to the error stream.
– Voo
Nov 19 at 16:32
50
@Voo: I would argue that any program that assumes writes to stderr indicate a failure is itself incorrect. The exit code of the process is what indicates whether or not it failed. If it was a failure, then the stderr output will explain why. If the process exited successfully (exit code zero) then stderr output should be considered informational output for a human user, with no particular machine-parseable semantic (it might contain human-readable warnings, for example), while stdout is the actual output of the program, possibly suitable for further processing.
– Daniel Pryden
Nov 19 at 16:58
22
@Voo: What programs are you describing? I'm not aware of any widely-used software package that behaves like you describe. I do know that there are programs that do, but it's not like I just made up the convention I describe above: that's the way the vast majority of programs in a Unix or Unix-like environment work, and to my knowledge, the way the vast majority of programs always have. I certainly wouldn't advocate for any program to avoid writing to stderr simply because some scripts don't handle it well.
– Daniel Pryden
Nov 19 at 18:05
|
show 5 more comments
19
This is particularly important when using printf for debugging a program that crashes. Putting the newline at the end of a printf means that stdout to the console gets flushed at each printf. (Note that when stdout is redirected to a file, the std libraries will usually do block buffering instead of line buffering, so that makes printf debugging a crash quite hard even with newline at the end.)
– Erik Eidt
Nov 19 at 14:33
24
@ErikEidt Note that you should usefprintf(STDERR, …)
instead, which is generally not buffered at all for diagnostic output.
– Deduplicator
Nov 19 at 16:29
4
@Deduplicator Writing diagnostic messages to the error stream has its downsides as well - many scripts assume a program has failed if something is written to the error stream.
– Voo
Nov 19 at 16:32
50
@Voo: I would argue that any program that assumes writes to stderr indicate a failure is itself incorrect. The exit code of the process is what indicates whether or not it failed. If it was a failure, then the stderr output will explain why. If the process exited successfully (exit code zero) then stderr output should be considered informational output for a human user, with no particular machine-parseable semantic (it might contain human-readable warnings, for example), while stdout is the actual output of the program, possibly suitable for further processing.
– Daniel Pryden
Nov 19 at 16:58
22
@Voo: What programs are you describing? I'm not aware of any widely-used software package that behaves like you describe. I do know that there are programs that do, but it's not like I just made up the convention I describe above: that's the way the vast majority of programs in a Unix or Unix-like environment work, and to my knowledge, the way the vast majority of programs always have. I certainly wouldn't advocate for any program to avoid writing to stderr simply because some scripts don't handle it well.
– Daniel Pryden
Nov 19 at 18:05
19
19
This is particularly important when using printf for debugging a program that crashes. Putting the newline at the end of a printf means that stdout to the console gets flushed at each printf. (Note that when stdout is redirected to a file, the std libraries will usually do block buffering instead of line buffering, so that makes printf debugging a crash quite hard even with newline at the end.)
– Erik Eidt
Nov 19 at 14:33
This is particularly important when using printf for debugging a program that crashes. Putting the newline at the end of a printf means that stdout to the console gets flushed at each printf. (Note that when stdout is redirected to a file, the std libraries will usually do block buffering instead of line buffering, so that makes printf debugging a crash quite hard even with newline at the end.)
– Erik Eidt
Nov 19 at 14:33
24
24
@ErikEidt Note that you should use
fprintf(STDERR, …)
instead, which is generally not buffered at all for diagnostic output.– Deduplicator
Nov 19 at 16:29
@ErikEidt Note that you should use
fprintf(STDERR, …)
instead, which is generally not buffered at all for diagnostic output.– Deduplicator
Nov 19 at 16:29
4
4
@Deduplicator Writing diagnostic messages to the error stream has its downsides as well - many scripts assume a program has failed if something is written to the error stream.
– Voo
Nov 19 at 16:32
@Deduplicator Writing diagnostic messages to the error stream has its downsides as well - many scripts assume a program has failed if something is written to the error stream.
– Voo
Nov 19 at 16:32
50
50
@Voo: I would argue that any program that assumes writes to stderr indicate a failure is itself incorrect. The exit code of the process is what indicates whether or not it failed. If it was a failure, then the stderr output will explain why. If the process exited successfully (exit code zero) then stderr output should be considered informational output for a human user, with no particular machine-parseable semantic (it might contain human-readable warnings, for example), while stdout is the actual output of the program, possibly suitable for further processing.
– Daniel Pryden
Nov 19 at 16:58
@Voo: I would argue that any program that assumes writes to stderr indicate a failure is itself incorrect. The exit code of the process is what indicates whether or not it failed. If it was a failure, then the stderr output will explain why. If the process exited successfully (exit code zero) then stderr output should be considered informational output for a human user, with no particular machine-parseable semantic (it might contain human-readable warnings, for example), while stdout is the actual output of the program, possibly suitable for further processing.
– Daniel Pryden
Nov 19 at 16:58
22
22
@Voo: What programs are you describing? I'm not aware of any widely-used software package that behaves like you describe. I do know that there are programs that do, but it's not like I just made up the convention I describe above: that's the way the vast majority of programs in a Unix or Unix-like environment work, and to my knowledge, the way the vast majority of programs always have. I certainly wouldn't advocate for any program to avoid writing to stderr simply because some scripts don't handle it well.
– Daniel Pryden
Nov 19 at 18:05
@Voo: What programs are you describing? I'm not aware of any widely-used software package that behaves like you describe. I do know that there are programs that do, but it's not like I just made up the convention I describe above: that's the way the vast majority of programs in a Unix or Unix-like environment work, and to my knowledge, the way the vast majority of programs always have. I certainly wouldn't advocate for any program to avoid writing to stderr simply because some scripts don't handle it well.
– Daniel Pryden
Nov 19 at 18:05
|
show 5 more comments
up vote
66
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.
22
This is one of the oldest debates in software engineering: is it better to use newlines (or, in a programming language, another "end of statement" marker like a semicolon) as line terminators or line separators? Both approaches have their pros and cons. The Windows world has mostly settled on the idea that the newline sequence (which is typically CR LF there) is a line separator, and thus the last line in a file doesn't need to end with it. In the Unix world, though, a newline sequence (LF) is a line terminator, and many programs are built around this assumption.
– Daniel Pryden
Nov 19 at 13:54
29
POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
– pipe
Nov 19 at 14:52
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
Nov 19 at 16:11
3
@Baldrickk Right. I have updated my answer to be more affirmative, now.
– cmaster
Nov 19 at 16:18
C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
– R..
Nov 21 at 18:26
|
show 1 more comment
up vote
66
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.
22
This is one of the oldest debates in software engineering: is it better to use newlines (or, in a programming language, another "end of statement" marker like a semicolon) as line terminators or line separators? Both approaches have their pros and cons. The Windows world has mostly settled on the idea that the newline sequence (which is typically CR LF there) is a line separator, and thus the last line in a file doesn't need to end with it. In the Unix world, though, a newline sequence (LF) is a line terminator, and many programs are built around this assumption.
– Daniel Pryden
Nov 19 at 13:54
29
POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
– pipe
Nov 19 at 14:52
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
Nov 19 at 16:11
3
@Baldrickk Right. I have updated my answer to be more affirmative, now.
– cmaster
Nov 19 at 16:18
C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
– R..
Nov 21 at 18:26
|
show 1 more comment
up vote
66
down vote
up vote
66
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.
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.
edited Nov 19 at 16:17
answered Nov 19 at 13:31
cmaster
6,24311220
6,24311220
22
This is one of the oldest debates in software engineering: is it better to use newlines (or, in a programming language, another "end of statement" marker like a semicolon) as line terminators or line separators? Both approaches have their pros and cons. The Windows world has mostly settled on the idea that the newline sequence (which is typically CR LF there) is a line separator, and thus the last line in a file doesn't need to end with it. In the Unix world, though, a newline sequence (LF) is a line terminator, and many programs are built around this assumption.
– Daniel Pryden
Nov 19 at 13:54
29
POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
– pipe
Nov 19 at 14:52
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
Nov 19 at 16:11
3
@Baldrickk Right. I have updated my answer to be more affirmative, now.
– cmaster
Nov 19 at 16:18
C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
– R..
Nov 21 at 18:26
|
show 1 more comment
22
This is one of the oldest debates in software engineering: is it better to use newlines (or, in a programming language, another "end of statement" marker like a semicolon) as line terminators or line separators? Both approaches have their pros and cons. The Windows world has mostly settled on the idea that the newline sequence (which is typically CR LF there) is a line separator, and thus the last line in a file doesn't need to end with it. In the Unix world, though, a newline sequence (LF) is a line terminator, and many programs are built around this assumption.
– Daniel Pryden
Nov 19 at 13:54
29
POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
– pipe
Nov 19 at 14:52
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
Nov 19 at 16:11
3
@Baldrickk Right. I have updated my answer to be more affirmative, now.
– cmaster
Nov 19 at 16:18
C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
– R..
Nov 21 at 18:26
22
22
This is one of the oldest debates in software engineering: is it better to use newlines (or, in a programming language, another "end of statement" marker like a semicolon) as line terminators or line separators? Both approaches have their pros and cons. The Windows world has mostly settled on the idea that the newline sequence (which is typically CR LF there) is a line separator, and thus the last line in a file doesn't need to end with it. In the Unix world, though, a newline sequence (LF) is a line terminator, and many programs are built around this assumption.
– Daniel Pryden
Nov 19 at 13:54
This is one of the oldest debates in software engineering: is it better to use newlines (or, in a programming language, another "end of statement" marker like a semicolon) as line terminators or line separators? Both approaches have their pros and cons. The Windows world has mostly settled on the idea that the newline sequence (which is typically CR LF there) is a line separator, and thus the last line in a file doesn't need to end with it. In the Unix world, though, a newline sequence (LF) is a line terminator, and many programs are built around this assumption.
– Daniel Pryden
Nov 19 at 13:54
29
29
POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
– pipe
Nov 19 at 14:52
POSIX even defines a line as "A sequence of zero or more non-newline characters plus a terminating newline character."
– pipe
Nov 19 at 14:52
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
Nov 19 at 16:11
Given that as @pipe says, it's in the POSIX specification, we can probably call it de jure as opposed to de facto as the answer suggests?
– Baldrickk
Nov 19 at 16:11
3
3
@Baldrickk Right. I have updated my answer to be more affirmative, now.
– cmaster
Nov 19 at 16:18
@Baldrickk Right. I have updated my answer to be more affirmative, now.
– cmaster
Nov 19 at 16:18
C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
– R..
Nov 21 at 18:26
C also makes this convention for source files: a non-empty source file that does not end with a newline produces undefined behavior.
– R..
Nov 21 at 18:26
|
show 1 more comment
up vote
28
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.
2
Something similar happens with programs that are interrupted in an interactive shell - if a partial line is printed (missing its newline), then the shell gets confused about which column the cursor is on, making it hard to edit the next command line. Unless you add a leading newline to your$PS1
, which would then be an irritant following conventional programs.
– Toby Speight
Nov 21 at 23:16
add a comment |
up vote
28
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.
2
Something similar happens with programs that are interrupted in an interactive shell - if a partial line is printed (missing its newline), then the shell gets confused about which column the cursor is on, making it hard to edit the next command line. Unless you add a leading newline to your$PS1
, which would then be an irritant following conventional programs.
– Toby Speight
Nov 21 at 23:16
add a comment |
up vote
28
down vote
up vote
28
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.
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.
edited Nov 19 at 20:18
answered Nov 19 at 20:13
The Guy with The Hat
418310
418310
2
Something similar happens with programs that are interrupted in an interactive shell - if a partial line is printed (missing its newline), then the shell gets confused about which column the cursor is on, making it hard to edit the next command line. Unless you add a leading newline to your$PS1
, which would then be an irritant following conventional programs.
– Toby Speight
Nov 21 at 23:16
add a comment |
2
Something similar happens with programs that are interrupted in an interactive shell - if a partial line is printed (missing its newline), then the shell gets confused about which column the cursor is on, making it hard to edit the next command line. Unless you add a leading newline to your$PS1
, which would then be an irritant following conventional programs.
– Toby Speight
Nov 21 at 23:16
2
2
Something similar happens with programs that are interrupted in an interactive shell - if a partial line is printed (missing its newline), then the shell gets confused about which column the cursor is on, making it hard to edit the next command line. Unless you add a leading newline to your
$PS1
, which would then be an irritant following conventional programs.– Toby Speight
Nov 21 at 23:16
Something similar happens with programs that are interrupted in an interactive shell - if a partial line is printed (missing its newline), then the shell gets confused about which column the cursor is on, making it hard to edit the next command line. Unless you add a leading newline to your
$PS1
, which would then be an irritant following conventional programs.– Toby Speight
Nov 21 at 23:16
add a comment |
up vote
16
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:
- a high signal-to-noise ratio (aka simple but not simpler)
- 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).
17
Yes,"okn"
is much better than"nok"
...
– cmaster
Nov 19 at 22:17
@cmaster: Reminds me of having read about MacOS using Pascal-string APIs in C, which required prefixing all string literals with a magic escape code like"pFoobar"
.
– grawity
yesterday
add a comment |
up vote
16
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:
- a high signal-to-noise ratio (aka simple but not simpler)
- 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).
17
Yes,"okn"
is much better than"nok"
...
– cmaster
Nov 19 at 22:17
@cmaster: Reminds me of having read about MacOS using Pascal-string APIs in C, which required prefixing all string literals with a magic escape code like"pFoobar"
.
– grawity
yesterday
add a comment |
up vote
16
down vote
up vote
16
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:
- a high signal-to-noise ratio (aka simple but not simpler)
- 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).
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:
- a high signal-to-noise ratio (aka simple but not simpler)
- 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).
answered Nov 19 at 20:42
Alex Vong
33913
33913
17
Yes,"okn"
is much better than"nok"
...
– cmaster
Nov 19 at 22:17
@cmaster: Reminds me of having read about MacOS using Pascal-string APIs in C, which required prefixing all string literals with a magic escape code like"pFoobar"
.
– grawity
yesterday
add a comment |
17
Yes,"okn"
is much better than"nok"
...
– cmaster
Nov 19 at 22:17
@cmaster: Reminds me of having read about MacOS using Pascal-string APIs in C, which required prefixing all string literals with a magic escape code like"pFoobar"
.
– grawity
yesterday
17
17
Yes,
"okn"
is much better than "nok"
...– cmaster
Nov 19 at 22:17
Yes,
"okn"
is much better than "nok"
...– cmaster
Nov 19 at 22:17
@cmaster: Reminds me of having read about MacOS using Pascal-string APIs in C, which required prefixing all string literals with a magic escape code like
"pFoobar"
.– grawity
yesterday
@cmaster: Reminds me of having read about MacOS using Pascal-string APIs in C, which required prefixing all string literals with a magic escape code like
"pFoobar"
.– grawity
yesterday
add a comment |
up vote
15
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.
New contributor
If every independent output item is supposed to appear on its own line, trailing new lines can work fine. If multiple items should be consolidated when practical, however, things get more complicated. If it's practical to feed all output through a common routine, an operation to insert a clear-to-end-of-line if the last character was a CR, nothing if the last character was a newline, and a newline if the last character was anything else, may be helpful if programs need to do something other than output a sequence of independent lines.
– supercat
Nov 20 at 20:40
add a comment |
up vote
15
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.
New contributor
If every independent output item is supposed to appear on its own line, trailing new lines can work fine. If multiple items should be consolidated when practical, however, things get more complicated. If it's practical to feed all output through a common routine, an operation to insert a clear-to-end-of-line if the last character was a CR, nothing if the last character was a newline, and a newline if the last character was anything else, may be helpful if programs need to do something other than output a sequence of independent lines.
– supercat
Nov 20 at 20:40
add a comment |
up vote
15
down vote
up vote
15
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.
New contributor
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.
New contributor
edited Nov 19 at 17:14
New contributor
answered Nov 19 at 17:07
alephzero
25925
25925
New contributor
New contributor
If every independent output item is supposed to appear on its own line, trailing new lines can work fine. If multiple items should be consolidated when practical, however, things get more complicated. If it's practical to feed all output through a common routine, an operation to insert a clear-to-end-of-line if the last character was a CR, nothing if the last character was a newline, and a newline if the last character was anything else, may be helpful if programs need to do something other than output a sequence of independent lines.
– supercat
Nov 20 at 20:40
add a comment |
If every independent output item is supposed to appear on its own line, trailing new lines can work fine. If multiple items should be consolidated when practical, however, things get more complicated. If it's practical to feed all output through a common routine, an operation to insert a clear-to-end-of-line if the last character was a CR, nothing if the last character was a newline, and a newline if the last character was anything else, may be helpful if programs need to do something other than output a sequence of independent lines.
– supercat
Nov 20 at 20:40
If every independent output item is supposed to appear on its own line, trailing new lines can work fine. If multiple items should be consolidated when practical, however, things get more complicated. If it's practical to feed all output through a common routine, an operation to insert a clear-to-end-of-line if the last character was a CR, nothing if the last character was a newline, and a newline if the last character was anything else, may be helpful if programs need to do something other than output a sequence of independent lines.
– supercat
Nov 20 at 20:40
If every independent output item is supposed to appear on its own line, trailing new lines can work fine. If multiple items should be consolidated when practical, however, things get more complicated. If it's practical to feed all output through a common routine, an operation to insert a clear-to-end-of-line if the last character was a CR, nothing if the last character was a newline, and a newline if the last character was anything else, may be helpful if programs need to do something other than output a sequence of independent lines.
– supercat
Nov 20 at 20:40
add a comment |
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");
I did once improveispell.el
to cope better with that. I admit it was more oftent
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">
orContent-Language: gd
), but never did get a Round Tuit. And the maintainer rejected my patch outright. :-(
– Toby Speight
Nov 21 at 23:28
@TobySpeight Here's a round toit. Look forward to trying your re-improvedispell.el
.
– chux
Nov 21 at 23:33
add a comment |
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");
I did once improveispell.el
to cope better with that. I admit it was more oftent
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">
orContent-Language: gd
), but never did get a Round Tuit. And the maintainer rejected my patch outright. :-(
– Toby Speight
Nov 21 at 23:28
@TobySpeight Here's a round toit. Look forward to trying your re-improvedispell.el
.
– chux
Nov 21 at 23:33
add a comment |
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");
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");
edited Nov 21 at 5:04
answered Nov 21 at 4:56
chux
32118
32118
I did once improveispell.el
to cope better with that. I admit it was more oftent
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">
orContent-Language: gd
), but never did get a Round Tuit. And the maintainer rejected my patch outright. :-(
– Toby Speight
Nov 21 at 23:28
@TobySpeight Here's a round toit. Look forward to trying your re-improvedispell.el
.
– chux
Nov 21 at 23:33
add a comment |
I did once improveispell.el
to cope better with that. I admit it was more oftent
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">
orContent-Language: gd
), but never did get a Round Tuit. And the maintainer rejected my patch outright. :-(
– Toby Speight
Nov 21 at 23:28
@TobySpeight Here's a round toit. Look forward to trying your re-improvedispell.el
.
– chux
Nov 21 at 23:33
I did once improve
ispell.el
to cope better with that. I admit it was more often t
that was the problem, and it could be avoided simply by breaking the string into multiple tokens, but it was just a side-effect of more general "ignore" work, to selectively skip non-text parts of HTML or MIME multipart bodies, and non-comment parts of code. I did always mean to extend it to switching languages where there's appropriate metadata (e.g. <p lang="de_AT">
or Content-Language: gd
), but never did get a Round Tuit. And the maintainer rejected my patch outright. :-(– Toby Speight
Nov 21 at 23:28
I did once improve
ispell.el
to cope better with that. I admit it was more often t
that was the problem, and it could be avoided simply by breaking the string into multiple tokens, but it was just a side-effect of more general "ignore" work, to selectively skip non-text parts of HTML or MIME multipart bodies, and non-comment parts of code. I did always mean to extend it to switching languages where there's appropriate metadata (e.g. <p lang="de_AT">
or Content-Language: gd
), but never did get a Round Tuit. And the maintainer rejected my patch outright. :-(– Toby Speight
Nov 21 at 23:28
@TobySpeight Here's a round toit. Look forward to trying your re-improved
ispell.el
.– chux
Nov 21 at 23:33
@TobySpeight Here's a round toit. Look forward to trying your re-improved
ispell.el
.– chux
Nov 21 at 23:33
add a comment |
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.
1
Could you explain why this version is easier to write than one with trailing newlines? In this example it is not apparent to me. Instead I could see problems arising with the next output being added to the same line as"nProcessing"
.
– Raimund Krämer
Nov 21 at 15:18
Like Raimund, I can also see problems arising from working like this. You need to consider surrounding prints when callingprintf
. What if you wanted to conditionalize the whole "Initializing" line? You'd have to include the "Procesing" line in that condition to know if you should prefix with a newline or not. If there's another print ahead and you need to conditionalize the "Processing" line, you would also need to include the next print in that condition to know if you should prefix with another newline, and so forth for each print.
– JoL
Nov 21 at 16:20
1
I agree with the principle, but the example isn't a good one. A more relevant example would be with code which is supposed to output some number of items per line. If the output is supposed to start with a header that ends with a newline, and each line is supposed to start with a header, it may be easier to say, e.g.if ((addr & 0x0F)==0) printf("n%08X:", addr);
and unconditionally add a newline to the output at the end, than to use separate code for each line's header and the trailing newline.
– supercat
yesterday
add a comment |
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.
1
Could you explain why this version is easier to write than one with trailing newlines? In this example it is not apparent to me. Instead I could see problems arising with the next output being added to the same line as"nProcessing"
.
– Raimund Krämer
Nov 21 at 15:18
Like Raimund, I can also see problems arising from working like this. You need to consider surrounding prints when callingprintf
. What if you wanted to conditionalize the whole "Initializing" line? You'd have to include the "Procesing" line in that condition to know if you should prefix with a newline or not. If there's another print ahead and you need to conditionalize the "Processing" line, you would also need to include the next print in that condition to know if you should prefix with another newline, and so forth for each print.
– JoL
Nov 21 at 16:20
1
I agree with the principle, but the example isn't a good one. A more relevant example would be with code which is supposed to output some number of items per line. If the output is supposed to start with a header that ends with a newline, and each line is supposed to start with a header, it may be easier to say, e.g.if ((addr & 0x0F)==0) printf("n%08X:", addr);
and unconditionally add a newline to the output at the end, than to use separate code for each line's header and the trailing newline.
– supercat
yesterday
add a comment |
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.
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.
answered Nov 19 at 13:09
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
Nov 21 at 15:18
Like Raimund, I can also see problems arising from working like this. You need to consider surrounding prints when callingprintf
. What if you wanted to conditionalize the whole "Initializing" line? You'd have to include the "Procesing" line in that condition to know if you should prefix with a newline or not. If there's another print ahead and you need to conditionalize the "Processing" line, you would also need to include the next print in that condition to know if you should prefix with another newline, and so forth for each print.
– JoL
Nov 21 at 16:20
1
I agree with the principle, but the example isn't a good one. A more relevant example would be with code which is supposed to output some number of items per line. If the output is supposed to start with a header that ends with a newline, and each line is supposed to start with a header, it may be easier to say, e.g.if ((addr & 0x0F)==0) printf("n%08X:", addr);
and unconditionally add a newline to the output at the end, than to use separate code for each line's header and the trailing newline.
– supercat
yesterday
add a comment |
1
Could you explain why this version is easier to write than one with trailing newlines? In this example it is not apparent to me. Instead I could see problems arising with the next output being added to the same line as"nProcessing"
.
– Raimund Krämer
Nov 21 at 15:18
Like Raimund, I can also see problems arising from working like this. You need to consider surrounding prints when callingprintf
. What if you wanted to conditionalize the whole "Initializing" line? You'd have to include the "Procesing" line in that condition to know if you should prefix with a newline or not. If there's another print ahead and you need to conditionalize the "Processing" line, you would also need to include the next print in that condition to know if you should prefix with another newline, and so forth for each print.
– JoL
Nov 21 at 16:20
1
I agree with the principle, but the example isn't a good one. A more relevant example would be with code which is supposed to output some number of items per line. If the output is supposed to start with a header that ends with a newline, and each line is supposed to start with a header, it may be easier to say, e.g.if ((addr & 0x0F)==0) printf("n%08X:", addr);
and unconditionally add a newline to the output at the end, than to use separate code for each line's header and the trailing newline.
– supercat
yesterday
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
Nov 21 at 15:18
Could you explain why this version is easier to write than one with trailing newlines? In this example it is not apparent to me. Instead I could see problems arising with the next output being added to the same line as
"nProcessing"
.– Raimund Krämer
Nov 21 at 15:18
Like Raimund, I can also see problems arising from working like this. You need to consider surrounding prints when calling
printf
. What if you wanted to conditionalize the whole "Initializing" line? You'd have to include the "Procesing" line in that condition to know if you should prefix with a newline or not. If there's another print ahead and you need to conditionalize the "Processing" line, you would also need to include the next print in that condition to know if you should prefix with another newline, and so forth for each print.– JoL
Nov 21 at 16:20
Like Raimund, I can also see problems arising from working like this. You need to consider surrounding prints when calling
printf
. What if you wanted to conditionalize the whole "Initializing" line? You'd have to include the "Procesing" line in that condition to know if you should prefix with a newline or not. If there's another print ahead and you need to conditionalize the "Processing" line, you would also need to include the next print in that condition to know if you should prefix with another newline, and so forth for each print.– JoL
Nov 21 at 16:20
1
1
I agree with the principle, but the example isn't a good one. A more relevant example would be with code which is supposed to output some number of items per line. If the output is supposed to start with a header that ends with a newline, and each line is supposed to start with a header, it may be easier to say, e.g.
if ((addr & 0x0F)==0) printf("n%08X:", addr);
and unconditionally add a newline to the output at the end, than to use separate code for each line's header and the trailing newline.– supercat
yesterday
I agree with the principle, but the example isn't a good one. A more relevant example would be with code which is supposed to output some number of items per line. If the output is supposed to start with a header that ends with a newline, and each line is supposed to start with a header, it may be easier to say, e.g.
if ((addr & 0x0F)==0) printf("n%08X:", addr);
and unconditionally add a newline to the output at the end, than to use separate code for each line's header and the trailing newline.– supercat
yesterday
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Nov 21 at 23:24
Toby Speight
32729
32729
add a comment |
add a comment |
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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
42
The last line would merge with the command prompt on linux without a trailing newline.
– GrandmasterB
Nov 19 at 17:08
4
If it "looks better" and it has no downside, that's a good enough reason to do it, IMO. Writing good code is no different to writing a good novel or a good technical paper - the devil is always in the detail.
– alephzero
Nov 19 at 17:20
5
Do
init()
andprocess_data()
print anything themselves? What would you expect the result to look like if they did?– Bergi
Nov 19 at 19:20
7
n
is a line terminator, not a line separator. This is evidenced by the fact that text files, on UNIX, almost always end inn
.– Jonathon Reinhart
Nov 20 at 18:40