When I'm writing a program in C, I often have to print a newline by itself. I know you can do this in at least two ways: printf("\n")
and putchar('\n')
, but I'm not sure which way is the best choice in terms of style and possibly efficiency. Are there any best practices for using one over the other? Does it really matter?
Here is a short code example that makes use of putchar . It prints an X , a space, and then a line of ten exclamation marks ( !!!!!!!!!! ) on the screen, then outputs a newline so that the next shell prompt will not occur on the same line.
The printf statement does not automatically append a newline to its output. It outputs only what the format string specifies. So if a newline is needed, you must include one in the format string.
The newline character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.
It will make no difference which one you chose if you're using a modern compiler[1]. Take for example the following C code.
#include <stdlib.h> #include <stdio.h> void foo(void) { putchar('\n'); } void bar(void) { printf("\n"); }
When compiled with gcc -O1
(optimizations enabled), we get the following (identical) machine code in both foo
and bar
:
movl $10, %edi popq %rbp jmp _putchar ## TAILCALL
Both foo
and bar
end up calling putchar('\n')
. In other words, modern C compilers are smart enough to optimize printf
calls very efficiently. Just use whichever one you think is more clear and readable.
cl
to be a modern compiler.Are there any best practices for using one over the other?
Let style drives the decision.
Since efficiency of execution is the same or nearly identical, use the style that best conveys the larger code's function.
If the function had lots of printf()
, stay with printf("\n")
.
Likewise for putchar('\n')
and puts("")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With