Reputation: 889
Which is better (in both performance and best practice) for printing only a newline:
putchar('\n')
or puts("")
From what I understand, putchar
outputs a single character and puts
outputs a string of characters. Forget about printf
.
I'm inclined to use puts
because it's shorter, but doing ("")
just feels wrong.
Which is faster and better?
Upvotes: 1
Views: 933
Reputation: 153348
A good compiler will emit the same optimized code for the below, so it is not a performance issue.
putchar('\n');
puts("");
Use the one that better conveys code's intent. This often depends on what else is being printed.
// Example 1
putchar('(');
putchar(ch);
putchar(')');
putchar('\n'); // Better choice
// puts("");
// Example 2
puts(name);
puts(rank);
puts(serial_number);
// putchar('\n');
puts(""); // Better choice
Upvotes: 2
Reputation: 3917
Theoretically, one requires a pointer, and an extra byte and the other doesn't. As well, one could require more instructions and potentially blow some i-cache
, which could be bad. In practice the difference between the two is almost certainly negligible though.
However, I'd still personally use putc
or putchar
just because the code is easier for anyone else to read and understand.
Upvotes: 5
Reputation: 3
Even though puts() allows you to output a string, you are outputting a string that has only a single character (the newline), so the result, and the performance, should be the same as using putchar().
Upvotes: 0
Reputation: 239831
Any speed difference between them is going to be insignificant, but putchar
is probably faster because it takes a single char argument.
Far more importantly, putchar('\n')
is saying what you mean, while puts("")
isn't.
Upvotes: 10