Difference between printf and puts in c programming language

In this tutorial we will learn what are the differences between printf and puts functions in c programming language?

Both functions are declared in stdio.h and used to send text/character stream to output stream (that will print on the standard output device).

But both are not same, their functionality, syntaxes and usages are different; basically they have two differences:

  1. printf can print the value of mixed type of variables but puts can’t print, puts has single parameter that is character array (character pointer).
  2. printf prints whatever you provide, it may be text, text + values etc without adding new line after the text while puts add one more character that is new line character (\n) just after the text/character stream.

So basically, if we want to print the string either we can use printf or puts, but if we want to add new line after the string, we should use puts.

printf

As we discussed in many posts that printf is used to print message/text/character stream along with the values of variables.

More about printf Read - Difference between printf and sprintf in c programming language.

puts

puts is used to print the string (character stream) on the output stream (that will print on the standard output device) with additional new line character (\n).

Here is the syntax

int puts(const char *text);

Here,

  • text is the character stream to be printed, it may be direct value within the double quotes or a character array variable.
  • Return type int - puts returns total number of printed characters excluding new line character (which adds automatically).

Here are three variations of puts

puts("Hello world!");
char msg[]="Hello world!";
puts(msg);
const char *msg="Hello world!";
puts(msg);

Consider the following program - how printf and puts printing the values?

#include <stdio.h>

int main(){
	
	printf("Using printf...\n");
	printf("This is line 1.");
	printf("This is line 2.");
	
	printf("\n\n");
	printf("Using puts...\n");
	puts("This is line 1.");
	puts("This is line 2.");
	
	printf("End of main...\n");
	
	return 0;
}

Output

Using printf... 
This is line 1.This is line 2.

Using puts... 
This is line 1. 
This is line 2. 
End of main...

When "This is line 1." "This is line 2." are printing through printf both strings are printing in same line, while strings are printing through puts both strings are printing in separate line due to puts feature [Adds additional character new line after the string].





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.