What is the right way of printing non formatted string not ending in new line?
printf("foo: ");
vs
fputs("foo: ", stdout);
As mentioned in the title, the string is not formatted and does not end in a new line (so no puts). I am not sure about overheads and optimizations, so what is the rule of thumb is this case?
EDIT: Is it normal practice to use printf with non-formatted strings?
Answers
In the case where you simply want to print a non-formatted string without any special formatting or additional arguments, using fputs()
is generally more appropriate and efficient than using printf()
without any format specifiers.
Here's a breakdown of the differences and considerations:
-
printf("foo: ");
:printf()
is a formatted output function that is typically used when you need to format data before printing it.- In this case, you are using
printf()
without any format specifiers, which means it's being used essentially just to print a string. - While it will work, using
printf()
for simple string printing without formatting adds unnecessary overhead because it has to parse the format string even though there are no format specifiers. This can result in slightly slower performance compared to usingfputs()
.
-
fputs("foo: ", stdout);
:fputs()
is a file output function that is specifically designed for writing strings to a stream without any formatting.- It is more efficient for printing non-formatted strings because it doesn't have to parse any format specifiers.
- Since
fputs()
is designed for this specific task, it is generally more optimized for printing strings without any formatting overhead.
In terms of best practices, it's generally preferred to use fputs()
or similar functions like puts()
for printing non-formatted strings. This makes the code more clear and efficient, especially when there are no formatting needs.
Regarding your edit, it is not unusual to see printf()
used for printing non-formatted strings, especially in codebases where consistency or readability is prioritized over micro-optimizations. However, using fputs()
or puts()
is considered better practice when you're simply printing non-formatted strings. It's always a good idea to choose the most appropriate tool for the task at hand.