I've been reading many C code lastly.
I found that some times people use: printf("%s", "string")
instead of just printf("string")
with the peculiarity of "string"
being static, not coming from an input.
Does this have an impact on performance or is just code aesthetics? Is this a bad or good practice?
The f
in printf
is for “formatted”: printf
is doing work while it writes output. Using printf("string")
raises at least two issues:
printf
has to consider each character of the string to see if it contains %
characters indicating formatting instructions. If the string is long, this is a lot of unnecessary work. In contrast, with printf("%s", "string")
, printf
merely has to examine the %s
, see that it says to print a string, and then write the string to output without examining it for anything other than the null character indicating its end."string"
example may be merely a placeholder. Often, we want to write strings that are in buffers or other data storage, and often these strings are not constants but contain characters that have come from a user or other sources. In that case, we cannot merely pass the string to printf
to be printed, because, if it contains formatting instructions, printf
will interpret those instructions instead of merely printing the string.If we do want to merely write a string to standard output, that can be done with fwrite(string, length, 1, stdout)
or fputs(string, stdout)
. The former is preferable when we already know the length, as it does not require the called routine to examine the data again to find the null terminator.