2

I've seen this in code where just a normal string without any formatting is displayed using printf (e.g. printf("Hello World!\n"). Why not just use puts("Hello World") instead?

Bill Gates
  • 21
  • 1

5 Answers5

2

puts or fputs should be used whenever no variables must be formatted/printed. The following would give a problem:

 printf("How many %s is the interest?\n");

Especially when the string to print is passed as a variable, it can be hard to find the error.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
1

Also if you want to print something that has "%" it's recommended to use puts

boxHiccup
  • 128
  • 8
0

printf() is generally the preferred alternative, simply because it's more powerful and gives a programmer more control over their output.

F. Stephen Q
  • 4,208
  • 1
  • 19
  • 42
0

When you want to update your code later down the road, you might be using variables. puts() doesn't format variables, but printf() does. Also, puts() always adds the new line, so if you ever don't want a newline, then you'll want to switch to printf(). Basically, printf() allows you to maintain the code longer.

ShiningLight
  • 1,124
  • 12
  • 16
0

Why use printf("mystring\n") instead of just puts("mystring")?

Note: there are reasons not to use printf() like the apperance of the '%' character, but OP seems to want reasons for printf(line_of_text).

Example 1: in an embedded application (code space limited) that already uses printf(), puts() may cost additional program space.

Example 2: The output of puts() appends a '\n'. This behavior catches programmers who forget this and use puts("mystring\n"). Using printf("mystring\n") is explicit. Using fputs("mystring\n", stdout) is even better.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256