Sunday, October 13, 2013

What is the return type of the printf() function in C


printf  function return type is integer. As most of us knows that, printf function is used to print content in the specified format on the standard output. It returns the no.of characters it printed on the standard out put device. i.e for hello string, printf function returns 5 as length of the string is 5 and for integer value 200, printf returns 3  as 200 contains three characters. and for float value 20.034 it returns 6 as it has 6 characters including dot. printf treats \n as a character, so if you use \n in the printf function, return value includes \n as well. sample code and syntax , see below.

Syntax for printf function in C:


int printf(const char * restrict format, ...)


Example with characters:

#include<stdio.h>
int main()
{
    int i = printf("string is %s","hello");
    int j = printf("\n%s","hello");
    printf("\ni value is %d\n",i);
    printf("j value is %d\n",j);
}

OutPut: 

string is hello
hello
i value is 15
j value is 6


Example with Integers:
#include<stdio.h>
int main()
{
    int j=200;
    int k=20;
    int i = printf("%d",j);
    int l = printf("\n%d",k);
    printf("\ni value is %d\n",i);
    printf("l value is %d\n",l);
}
OutPut: 

200
20
i value is 3
l value is 3


Example with Float and character:

#include#include<stdio.h>
int main()
{
    float k=20.034;
    int c='a';
    int i = printf("%d",c);
    int a = printf("%c",c);
    int l = printf("\n%f",k);
    printf("\ni value is %d\n",i);
    printf("a value is %d\n",a);
    printf("l value is %d\n",l);
}

OutPut:

97a
20.034000
i value is 2
a value is 1
l value is 10

No comments:

Popular Posts