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

前端 未结 10 2093
长发绾君心
长发绾君心 2020-12-07 07:27

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

相关标签:
10条回答
  • 2020-12-07 07:51

    (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).

    0 讨论(0)
  • 2020-12-07 07:54

    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).

    0 讨论(0)
  • 2020-12-07 07:58

    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.

    0 讨论(0)
  • 2020-12-07 08:00

    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...

    0 讨论(0)
提交回复
热议问题