Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
You are watching: How to print a new line in c
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(”
“) and putchar(”
“), 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?

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 #include void foo(void) { putchar(”
“);}void bar(void) { printf(”
“);}When compiled with gcc -O1 (optimizations enabled), we get the following (identical) machine code in both foo and bar:
movl $10, %edipopq %rbpjmp _putchar ## TAILCALLBoth foo and bar end up calling putchar(”
“). 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.
I do not consider MS”s cl to be a modern compiler.
Are there any best practices for using one over the other?
Let style drives the decision.
See more: Samsung Note 5 Keyboard Cover For Galaxy Note 5 & S6 Edge+, Keyboard: Samsung Galaxy Note5
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(”
“).
Likewise for putchar(”
“) and puts(“”)

printf and putchar are both stdio functions, so they both write to the same FILE handle (rather than directly to the file descriptor).
However, printf is far heavier since the first argument is a format string that needs to be scanned for replacement expressions and escapes.
So, both printf(”
“) and putchar(”
“) will do the same thing, but the latter will be faster.
See more: What Kind Of Dog Is Jim On Mike And Molly, Griffon Bruxellois
It doesn”t really matter. I never encountered a case were printing to the console ever matter to someone in terms functions choice or effiency.
printf is much slower because the format string is parsed at runtime. Of course, the average homework program or simple Project Euler solution is so small that wasting a few CPU cycles doesn”t matter anyway.
I would go with putchar as the string in printf needs to be parsed. Should be slightly quicker – but probably not a lot in it.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev2021.9.21.40262
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.