Function returning printf as parameter



In this example, we will be learning, how can we write function returning printf statement ? Tutorial also explains the flow of program execution.

Function returning printf as parameter

#include<stdio.h>
#include<conio.h>
int func1() {
   return(printf("Hello"));
}
void main()
{
  int i;
  i = func1();
  printf("Value of i = %d",i);
}

Output :

Hello
Value of i = 5

Program explanation

We know that, printf statement returns the integer value i.e total number of characters printed on the screen.

Example Return Value Explanation
printf("Hello"); 5 Total Value printed on screen = 5
printf("Hi Abhi"); 7 Space is considered as printable character
printf("123"); 3 Digits can be considered as printable
printf("hi\n\t"); 4 \t and \n are considered as single character

In the above example firstly printf gets executed and the return value of printf statement is returned to main function.

Flow of execution

  1. Firstly func1() is called from the main function.
  2. In the func1() function printf() statement is called.
  3. It will print the message on the screen and return value of the printf() statement will be returned to main() function
  4. So function func1() will return integer 5 to main function and return value gets stored inside the variable 'i'

Function passing printf as parameter

We already know instead writing function returning printf, we can also pass printf as parameter to the function. Working of the printf statement as parameter is shown in the below program -

#include<stdio.h>
int sum(int i,int j) {
   return(i+j);
}
void main()
{
  int i;
  i = sum(printf("Hi\n"),printf("Hello\n"));
  printf("Value of i = %d",i);
}

Output :

Hello
Hi
Value of i = 9

In the above example 2nd parameter i.e 2nd printf() statement is printed firstly on the screen because the comma operator returns the rightmost operand

Now when printf statement gets executed completely then function gets invoked like this -

i = sum(printf("Hi\n"),printf("Hello\n"));
  = sum(3,6);
  = 9