I heard that you should avoid leading newlines when using printf
. So that instead of printf("\nHello World!")
you should use printf("Hello World!\n")
In this particular example above it does not make sense, since the output would be different, but consider this:
printf("Initializing");
init();
printf("\nProcessing");
process_data();
printf("\nExiting");
compared to:
printf("Initializing\n");
init();
printf("Processing\n");
process_data();
printf("Exiting");
I cannot see any benefit with trailing newlines, except that it looks better. Is there any other reason?
EDIT:
I'll address the close votes here and now. I don't think this belong to Stack overflow, because this question is mainly about design. I would also say that although it may be opinions to this matter, Kilian Foth's answer and cmaster's answer proves that there are indeed very objective benefits with one approach.
bash
will print the prompt immediately wherever the cursor may be, butzsh
will put a mark there and start the prompt on the next line. – Daniel Pryden Nov 19 '18 at 18:16init()
andprocess_data()
print anything themselves? What would you expect the result to look like if they did? – Bergi Nov 19 '18 at 19:20printf
ing a constant string which always has a newline at the end, considerputs
. Your compiler might optimize the calls into the same assembly, but it's better to be explicit about what you want to do. – Nov 20 '18 at 18:12print
prints newline before printing the object. IOW, the "traditional Lisp output paradigm" conforms to your "leading newline idea". Not that this is exceptionally convenient... – sds Nov 20 '18 at 18:23\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 '18 at 18:40echo -n my_output
, then I'll seemy_outputpeter@volta:/tmp$
with the cursor at the end of that waiting for me to type the next command. You should always end your program's output with a newline unless you have a very specific reason. – Peter Cordes Nov 20 '18 at 20:53printf("Exiting");
should beprintf("Exiting\n");
. – JoL Nov 21 '18 at 01:47%
character (for EOF) and a newline to the console if the EOF would be on the same light as the current prompt. – Bakuriu Nov 21 '18 at 20:40