C return value of printf



In C Programming we are repeatedly using printf statement. This tutorial explains what is the return value of printf () statement in C Programming.

Return value of printf () function

  1. Printf Statement is used to print something on console (on screen).
  2. Printf is predefined function is C programming language declared in stdio.h header file.
  3. Return value of printf () statement is an integer i.e printf statement returns the total number of characters successfully printed on the screen.

Program 1 : Assigning Value of printf

#include<stdio.h>
void main()
{
   int count = printf("Hello");
   printf("\nValue of count : %d",count);
}

Output :

Hello
Value of count : 5

In the above example we have assigned the return value of printf() statement to a integer variable. Thus output of the above program would be like -

Firstly it will print the hello and after printing the message total number of characters printed on the screen is 5 so it will assign value ‘5’ to an integer variable.

Program 2 : Using backslash characters

#include<stdio.h>
void main()
{
   int count = printf("Hello\n\n\n");
   printf("\nValue of count : %d",count);
}

Output :

Hello
Value of count : 8

In the program we have done just simple modification. We have just included the backslash characters in the printf statement. In this case return value of printf () statement includes all the backslash characters

Recommended Article : Backslash Characters

Program 3 : Nested Printf statements

#include<stdio.h>
void main()
{
   int a=20;
   printf("%d",printf("%d %d %d", a,a,a));
}

Output :

20 20 208

In the above example :

  1. Consider important rule which says - Always innermost printf will be executed First.
  2. Printf function returns the number of characters printed.
  3. In the Above Example of nested printf , Inner Printf Prints [20 20 20], here number of Characters Printed On Screen = 8 (including two Blank Spaces)
printf("%d",8);
  1. Outer Printf will Print “8”

Program 4 : Yet another example

#include<stdio.h>
void main()
{
   printf("%d",printf("Hello"));
}

Output :

Hello5