c

Why use print("%s", "string") and not just only print("string")?


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?


Solution

  • The f in printf is for “formatted”: printf is doing work while it writes output. Using printf("string") raises at least two issues:

    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.