Pages

Saturday, August 8, 2015

printf in C

Format:
int printf ( const char * format, ... );

Function:
This prints formatted output to stdout.
Writes the C string pointed by format to the standard output (stdout). If format includes format
specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers.

Return Value:
printf is a function and like any other function it has input parameters and a return value.
On success, the total number of characters written is returned. On failure, a negative number is returned. Thus the following C program makes perfect sense.

#include  

int main(void); // Declare main() and the fact that this program doesn’t use any passed parameters
int main()
{

    int i;
    int nCount = 0; // Always initialize your auto variables
    char szString[] = “We want to impress you %d\n”;

    for (i = 0; i < 5; i++)
    {
        nCount += printf(szString, i + 1);   //The return value of printf is 25 which is added to nCount
    }
    return (nCount); // Brackets around all return values
}

Output:

We want to impress you 1
The number of characters printed is 25
We want to impress you 2
The number of characters printed is 50
We want to impress you 3
The number of characters printed is 75
We want to impress you 4
The number of characters printed is 100
We want to impress you 5
The number of characters printed is 125
We want to impress you 6
The number of characters printed is 150

No comments:

Post a Comment