Closed 5 year 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 have the right to do this in at the very least two ways: printf("\n") and also putchar("\n"), but I"m not certain which way is the best choice in terms of style and also possibly efficiency. Room there any type of best practices for making use of one over the other? go it yes, really matter?
It will certainly make no distinction which one you decided if you"re making use of a modern-day compiler<1>. Take for example the following C code.
#include #include void foo(void) putchar("\n");void bar(void) printf("\n");When compiled with gcc -O1 (optimizations enabled), we acquire the following (identical) machine code in both foo and also bar:
movl $10, %edipopq %rbpjmp _putchar ## TAILCALLBoth foo and bar finish up calling putchar("\n"). In various other words, contemporary C compilers are smart enough to optimize printf calls an extremely efficiently. Just use whichever one girlfriend think is more clear and also readable.I execute not think about MS"s cl to it is in a modern-day compiler.
room there any type of best methods for making use of one end the other?
Let style drives the decision.
Since efficiency of execution is the same or virtually identical, usage the format that best conveys the bigger code"s function.
If the duty had several printf(), stay with printf("\n").
Likewise for putchar("\n") and also puts("")
printf and putchar space both stdio functions, so they both write to the same paper handle (rather than straight to the file descriptor).
However, printf is much heavier since the an initial argument is a format string that requirements to it is in scanned because that replacement expressions and escapes.
So, both printf("\n") and also putchar("\n") will execute 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 yes, really matter. I never encountered a case were printing come the console ever matter to someone in state functions an option or effiency.
printf is much slower since the format string is parsed at runtime. The course, the median homework regime or an easy Project Euler solution is so tiny that wasting a couple of CPU cycles doesn"t issue anyway.
I would certainly go with putchar as the wire in printf requirements to it is in parsed. Need to be slightly faster - however probably not a lot of in it.
site design / logo © 2021 stack Exchange Inc; user contributions licensed under cc by-sa. Rev2021.9.21.40262