Why you’ve never seen `puts()` in a C language example
puts()
can print string in C. At first, it looks quite useful. Short and easy format for print strings. Let’s check that. But Why it’s so hard to see in examples of C code?
What is puts()?
Before we find the reason let’s see how can we use this. First, we need to include a header file that has puts()
.
#include <stdio.h>
And now we can use what we want.
int main()
{
puts('Hola, mi nombre es Doyun.');
puts('Mucho gusto conocerte.');
}
We can use puts()
likes the above. So, simple. And we don’t need to use \n
it for changing lines. Looks perfect for printing ‘string’. Agree?
But, that’s all. That’s all that puts()
has. Notting more.
A solid alternative `printf`
But from my personal point of view, it is 100% useless. Why? Because we have a solid alternative option. printf()
.
For using printf()
you also need to include stdio.h
header file.
#include <stdio.h>
And the usage is the same as puts()
.
int main()
{
printf('Hola, mi nombre es Doyun.\n');
printf('Mucho gusto conocerte.');
}
The only thing different is that you need to add \n
for change line. It can be a little inconvenient, but if you just put up with it, it’s a huge advantage.
First printf()
can print more than string. For example…
int main()
{
printf('Hirving Lozano (1995 ~) : SSC Napoli');
printf('%s (%d ~) : %s', 'Hirving Lozano', 1995, 'SCC Napoli');
}
They both print the same message. Like the second one, print()
also can print int and another variable. And also you can calculate.
printf(“30 to Hexadecimal = %X\n”, 30);
These advantages encourage using printf
instead of puts
.
Then puts() is 100% useless?
No no, even as I said it's almost useless. puts()
also has its own strengths. Theoretically, puts
is faster than printf
if only string is printed. If you are outputting a string from a program that cares about processing speed, you should use puts()
.