Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use printf("\n") or putchar('\n') to print a newline in C? [closed]

Tags:

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?

like image 254
Courtney Pattison Avatar asked Dec 11 '15 19:12

Courtney Pattison


People also ask

Does Putchar print new line?

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.

Does printf print a newline?

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.

Why do you need \n in C?

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.


2 Answers

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.


  1. I do not consider MS's cl to be a modern compiler.
like image 129
DaoWen Avatar answered Oct 22 '22 18:10

DaoWen


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("")

like image 39
chux - Reinstate Monica Avatar answered Oct 22 '22 16:10

chux - Reinstate Monica