puts() and printf(), when and which to use?

Asked

Viewed 3,921 times

7

Data input requests are usually preceded by text indicative of what you wish to receive and usually do not have data to be formatted.

If variable data are not being presented in the request text, why do books and teachers always use the printf()? The function puts() is not used to display simple text?

2 answers

5


The two functions are equal, but the function puts() adds a line break equal to printf("\n")

But when using the puts() we have to be aware that only prints the string, we do not have control of the printf() where we can print something like printf("int: %d, float: %f", x, y)

#include <stdio.h>
main() {
    printf("Hello world!");
    return 0;
}

In this example of Hello world compiler converts the printf() for puts()

push rbp
mov rbp,rsp
mov edi,str.Helloworld!
call dword imp.puts
mov eax,0x0
pop rbp
ret

To conclude, the printf() is a little slower because you need to format the variables and concatenate to a string to be printed. But this difference is practically irrelevant.

  • Enlightening, since I’m just starting I’ll take it as a practice, when I just want to write texts like "Hello word!" I will use the puts(), so the compiler has one less task, and gain a little more in performance...msm the difference is practically irrelevant...grain, grain... kkk.

  • @J.Ferreira in general experienced programmers do not do this, nowadays there are zero reasons to use the puts().

  • These things I don’t understand, if the command has its advantages or at least has no disadvantages and in the end the compiler uses it too, because the community doesn’t use it? is there anywhere where these good practices are cited? (Rhetorical questions that would accept answers)

  • 1

    the puts() has many limitations, that’s why not used, even because the performance is equal to printf() that difference the compiler makes is insignificant

5

The basic difference is that the printf() has formatting and has a wider control of how to print the desired data, is a complete printing solution. The puts() is a very simple solution to play characters on the console, you have to deliver exactly what you want, it does not manipulate anything, so you cannot send a number or content with a text and wait for something visible as expected by a human. The only thing he does more than the printf() is to place a line break automatically.

I’ve answered more about him on What is the difference between puts() and fputs()?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.