[c] What is the difference between printf() and puts() in C?

I know you can print with printf() and puts(). I can also see that printf() allows you to interpolate variables and do formatting.

Is puts() merely a primitive version of printf(). Should it be used for every possible printf() without string interpolation?

This question is related to c string output printf puts

The answer is


In my experience, printf() hauls in more code than puts() regardless of the format string.

If I don't need the formatting, I don't use printf. However, fwrite to stdout works a lot faster than puts.

static const char my_text[] = "Using fwrite.\n";
fwrite(my_text, 1, sizeof(my_text) - sizeof('\0'), stdout);

Note: per comments, '\0' is an integer constant. The correct expression should be sizeof(char) as indicated by the comments.


the printf() function is used to print both strings and variables to the screen while the puts() function only permits you to print a string only to your screen.


Besides formatting, puts returns a nonnegative integer if successful or EOF if unsuccessful; while printf returns the number of characters printed (not including the trailing null).


(This is pointed out in a comment by Zan Lynx, but I think it deserves an aswer - given that the accepted answer doesn't mention it).

The essential difference between puts(mystr); and printf(mystr); is that in the latter the argument is interpreted as a formatting string. The result will be often the same (except for the added newline) if the string doesn't contain any control characters (%) but if you cannot rely on that (if mystr is a variable instead of a literal) you should not use it.

So, it's generally dangerous -and conceptually wrong- to pass a dynamic string as single argument of printf:

  char * myMessage;
  // ... myMessage gets assigned at runtime, unpredictable content
  printf(myMessage);  // <--- WRONG! (what if myMessage contains a '%' char?) 
  puts(myMessage);    // ok
  printf("%s\n",myMessage); // ok, equivalent to the previous, perhaps less efficient

The same applies to fputs vs fprintf (but fputs doesn't add the newline).


In simple cases, the compiler converts calls to printf() to calls to puts().

For example, the following code will be compiled to the assembly code I show next.

#include <stdio.h>
main() {
    printf("Hello world!");
    return 0;
}
push rbp
mov rbp,rsp
mov edi,str.Helloworld!
call dword imp.puts
mov eax,0x0
pop rbp
ret

In this example, I used GCC version 4.7.2 and compiled the source with gcc -o hello hello.c.


int puts(const char *s);

puts() writes the string s and a trailing newline to stdout.

int printf(const char *format, ...);

The function printf() writes output to stdout, under the control of a format string that specifies how subsequent arguments are converted for output.

I'll use this opportunity to ask you to read the documentation.


Right, printf could be thought of as a more powerful version of puts. printf provides the ability to format variables for output using format specifiers such as %s, %d, %lf, etc...


When comparing puts() and printf(), even though their memory consumption is almost the same, puts() takes more time compared to printf().


puts is the simple choice and adds a new line in the end and printfwrites the output from a formatted string.

See the documentation for puts and for printf.

I would recommend to use only printf as this is more consistent than switching method, i.e if you are debbugging it is less painfull to search all printfs than puts and printf. Most times you want to output a variable in your printouts as well, so puts is mostly used in example code.


Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to output

How to create multiple output paths in Webpack config Where does the slf4j log file get saved? CMake output/build directory Suppress console output in PowerShell Output grep results to text file, need cleaner output How to use python numpy.savetxt to write strings and float number to an ASCII file? How to read a CSV file from a URL with Python? How can I suppress column header output for a single SQL statement? How to recover closed output window in netbeans? How can I see normal print output created during pytest run?

Examples related to printf

How I can print to stderr in C? How can you print multiple variables inside a string using printf? Unsigned values in C How to print multiple variable lines in Java Scanf/Printf double variable C Format specifier %02x %i or %d to print integer in C using printf()? What is the printf format specifier for bool? printf() prints whole array Printf width specifier to maintain precision of floating-point value

Examples related to puts

What is the difference between printf() and puts() in C?